<template>
  <div
    class="lotteryMoney hideScrollBar"
    ref="scrollEl"
    :class="{
      'lotteryMoney-bottom': lottery && isShowPK,
      'lotteryMoney-bottom-max': lottery && isShowPK && pkCardShow.length > 0,
    }"
  >
    <!-- 背景图片 -->
    <img
      v-if="isSun"
      class="lotteryMoney-bg"
      src="/image/lotterymoney/jackpot-bgimg1-icon.png"
    />
    <img
      v-else
      class="lotteryMoney-bg"
      src="/image/lotterymoney/jackpot-bgimg0-icon.png"
    />
    <!-- 导航 -->
    <NavBar
      isFixed
      :title="$t('lotteryMoney.cjdyj')"
      isTransparent
      :navScorllOffset="60"
      navScorllColor="#fff"
      :scrollEl="scrollEl"
      :customBackFn="handleBack"
    />

    <template v-if="!lottery">
      <van-skeleton title :row="6" style="margin-top: 25px" />
      <van-skeleton style="margin-top: 25px">
        <template #template>
          <div :style="{ display: 'flex', width: '100%' }">
            <van-skeleton-image />
            <div :style="{ flex: 1, marginLeft: '16px' }">
              <van-skeleton-paragraph row-width="60%" />
              <van-skeleton-paragraph />
              <van-skeleton-paragraph />
              <van-skeleton-paragraph />
            </div>
          </div>
        </template>
      </van-skeleton>
    </template>
    <template v-else>
      <!-- 活动 -->
      <div class="content">
        <ClientOnly>
          <van-pull-refresh
            class="pull-refresh"
            v-model="pageData.loading"
            :pulling-text="t('mvp.other.text9')"
            :loosing-text="t('mvp.other.text10')"
            loading-text=" "
            @refresh="onRefreshRequest"
          >
            <!-- 兑奖 -->
            <div
              class="jackpot-left items-center"
              :class="{ 'jackpot-left-fail': activitytStatus == 4 }"
              @click="jumpPage('bdcToMoney')"
            >
              <img
                class="jackpot-left-icon"
                src="/image/lotterymoney/jackpot-dj1-icon.svg"
              />
            </div>
            <!-- 活动说明 -->
            <div
              class="jackpot-right"
              :class="{ 'jackpot-right-fail': activitytStatus == 4 }"
              @click="jumpPage('lotteryDesc')"
            >
              <img
                class="jackpot-right-icon"
                src="/image/lotterymoney/pledge-desc-icon.svg"
              />
            </div>
            <!-- 结算中,请稍等: 1.查询数据的请求超时，失败-->
            <div
              v-if="activitytStatus == 4 || isThredFail"
              class="lotteryMoney-wait items-center"
              :class="{ 'lotteryMoney-wait-sun': isSun }"
              @click="refreshClick"
            >
              <div
                class="lotteryMoney-wait-text items-center"
                :class="{ 'lotteryMoney-wait-text-sun': isSun }"
              >
                <img
                  v-if="isSun"
                  class="lotteryMoney-wait-icon"
                  src="/image/gth1.svg"
                />
                <img
                  v-else
                  class="lotteryMoney-wait-icon"
                  src="/image/gth.svg"
                />
                {{ $t("lotteryMoney.jszqsd") }}
              </div>
              <img
                v-if="isSun"
                class="lotteryMoney-wait-btn"
                src="/image/refresh1.svg"
              />
              <img
                v-else
                class="lotteryMoney-wait-btn"
                src="/image/refresh.svg"
              />
            </div>

            <!-- 日期 -->
            <div class="date items-center">
              <div
                v-for="(item, index) in day7"
                :key="index"
                class="date-item items-center"
                :class="{
                  'date-item-sun': index == 6,
                  'date-item-jh': !pageData.toDayIdx
                    ? item.isActivity
                    : pageData.toDayIdx == index + 1,
                  'date-item-jh-sun':
                    (!pageData.toDayIdx
                      ? item.isActivity
                      : pageData.toDayIdx == index + 1) && index == 6,
                  'date-item-cur': item.isActivity,
                  'date-item-cur-sun': item.isActivity && index == 6,
                }"
                @click.stop="changeDay(item.dayIdx)"
              >
                <div
                  class="date-item-sub"
                  :class="{
                    'date-item-sub-sun': index == 6,
                  }"
                >
                  <div
                    :class="{
                      'date-item-sub-jh':
                        item.isActivity && pageData.toDayIdx != index + 1,
                      'date-item-sub-jh-sun': item.isActivity && index == 6,
                    }"
                  >
                    {{ item.title }}
                  </div>
                </div>
                <template v-if="index == 6">
                  <img
                    v-if="globalStore.$state.language == 'VI'"
                    class="date-item-sun-tag"
                    src="/image/lotterymoney/super-sun-icon1.svg"
                  />
                  <img
                    v-else-if="globalStore.$state.language == 'pt'"
                    class="date-item-sun-tag"
                    src="/image/lotterymoney/super-sun-icon.svg"
                  />
                  <img
                    v-else
                    class="date-item-sun-tag"
                    src="/image/lotterymoney/super-sun-icon2.svg"
                  />
                </template>
              </div>
            </div>
            <!-- 活动已结束 -->
            <div v-if="activitytStatus == 3 || activitytStatus == 6">
              <LotteryEnd
                :lottery="lottery"
                :curDay="pageData.toDayIdx"
                :status="activitytStatus"
                :beginTimeTag="beginTimeTag"
                :firstStageEndTimeTag="firstStageEndTimeTag"
                :secondEndTimeTag="secondEndTimeTag"
                :isSun="isSun"
                :isDetail="false"
                :inviterInfo="lottery.inviterInfo"
              ></LotteryEnd>
            </div>
            <!-- 活动未开始/活动进行中 -->
            <div v-else class="m_lr">
              <!-- 奖池 -->
              <Jackpot
                :lottery="lottery"
                :activitytStatus="activitytStatus"
                :moneyValue="moneyValue"
                :moneyStart="moneyStart"
                :isSun="isSun"
              ></Jackpot>

              <!-- 哈希 PK 阶段 -->
              <!-- v-if="isShowPK"   -->
              <HashView
                :curDay="pageData.toDayIdx"
                :lottery="lottery"
                :activitytStatus="activitytStatus"
                :beginTimeTag="beginTimeTag"
                :firstStageEndTimeTag="firstStageEndTimeTag"
                :secondEndTimeTag="secondEndTimeTag"
                @lastPunter="animationendSecond(1)"
                @animationend="animationendSecond(2)"
              >
                <!-- 动画锚点 -->
                <div ref="hashViewRef"></div>
              </HashView>
              <!-- 活动未开始,活动进行中 -->
              <!-- <LotteryStart
                v-else
                :isSun="isSun"
                :curDay="pageData.toDayIdx"
                :lottery="lottery"
                :status="activitytStatus"
                :beginTimeTag="beginTimeTag"
                :firstStageEndTimeTag="firstStageEndTimeTag"
                :secondEndTimeTag="secondEndTimeTag"
                @lastPunter="countdownEnds"
              ></LotteryStart> -->
            </div>
            <!-- 中奖记录,下注记录,往期记录 -->
            <div
              class="jumps items-center"
              v-if="lottery.sessionId"
              :class="{
                'jumps-lr': activitytStatus == 3 || activitytStatus == 6,
              }"
              :style="{
                'min-height':
                  activitytStatus != 3 && lottery.superPool && !isSun
                    ? '122px'
                    : 'initial',
              }"
            >
              <div class="jumps-top items-center">
                <div
                  class="jumps-item items-center"
                  @click.stop="jumpPage('myBetRecord')"
                >
                  <img
                    class="jumps-item-img"
                    src="/image/lotterymoney/bottom-wdxz1-icon.svg"
                  />
                  <div class="jumps-item-btn">
                    {{ $t("lotteryMoney.wdxzjl") }}
                  </div>
                </div>
                <div
                  class="jumps-item items-center"
                  @click.stop="jumpPage('recordBet')"
                >
                  <img
                    class="jumps-item-img"
                    src="/image/lotterymoney/bottom-blxz-icon.svg"
                  />
                  <div class="jumps-item-btn">
                    {{ $t("lotteryMoney.recordBet") }}
                  </div>
                </div>
                <div
                  class="jumps-item items-center"
                  @click.stop="jumpPage('previousDraws')"
                >
                  <img
                    class="jumps-item-img"
                    src="/image/lotterymoney/bottom-wqjl-icon.svg"
                  />
                  <div class="jumps-item-btn">
                    {{ $t("lotteryMoney.wqcj") }}
                  </div>
                </div>
              </div>
              <!-- 周一 - 周六/周日资格组件 -->
              <Qualification
                v-if="!isSun"
                :lottery="lottery"
                :activitytStatus="activitytStatus"
                @jump="changeDay(7)"
              ></Qualification>
            </div>
            <!-- 邀请好友来抽奖 -->
            <div
              v-if="
                lotteryMoneyStore.isShowInviteLottery && activitytStatus != 3
              "
              class="inviteFriends"
              :class="{
                'inviteFriends-end':
                  activitytStatus == 3 || activitytStatus == 6,
              }"
              @click="jumpPage('inviteFriendsMonery')"
            >
              <!-- 标题 -->
              <div class="inviteFriends-title items-center">
                <div class="inviteFriends-title-text">
                  {{ $t("inviteFriends.yqhylcj") }}
                </div>
                <img
                  class="inviteFriends-title-img"
                  src="/image/jt-right-icon.svg"
                />
              </div>
              <!-- 信息 -->
              <div class="inviteFriends-info items-center">
                <img
                  class="inviteFriends-info-leftimg"
                  src="/image/lotterymoney/inviteFriends-leftimg-icon.svg"
                />
                <img
                  class="inviteFriends-info-rightimg"
                  src="/image/lotterymoney/inviteFriends-rightimg-icon.svg"
                />
                <!-- logo -->
                <img
                  class="inviteFriends-info-logo"
                  src="/image/lotterymoney/inviteFriends-rightlogo-icon.svg"
                />

                <div class="inviteFriends-info-title">
                  {{ $t("inviteFriends.mthdjl").split("60000")[0] }}
                  <span
                    style="color: #f29301; font-weight: 1000; font-size: 13px"
                  >
                    35,000
                  </span>
                  {{ $t("inviteFriends.mthdjl").split("60000")[1] }}
                </div>
                <div class="inviteFriends-info-desc">
                  {{ $t("inviteFriends.hycwdyjjlfn30").split("30%")[0] }}
                  <span style="color: #f29301; font-weight: 700"> 30% </span>
                  {{ $t("inviteFriends.hycwdyjjlfn30").split("30%")[1] }}
                </div>
              </div>
            </div>
          </van-pull-refresh>
        </ClientOnly>
      </div>
      <div v-if="true" class="footer items-center">
        <!-- 下注按钮 -->
        <div class="footer-bottom items-center">
          <div
            class="footer-btn-border"
            :class="{
              'footer-btn-border-disabled': true,
            }"
          >
            <div
              class="footer-btn"
              :class="{
                'footer-btn-disabled': true && !isSun,
                'footer-btn-disabled-sun': true && isSun,
                'footer-btn-sun': !true && isSun,
              }"
            >
              {{ $t("lotteryMoney.gcyzj") }}
            </div>
          </div>
          <!-- 底部下注数量和队伍描述 -->
          <div class="footer-desc">
            {{ $t("lotteryMoney.bqyxzcs") }}
            <span
              v-if="lottery"
              :class="{
                'footer-desc-value': !isSun,
                'footer-desc-sun': isSun,
              }"
              >{{ lottery ? lottery.sessionDrawCount : 0 }}</span
            >
            ，{{ $t("lotteryMoney.nddw")
            }}<span
              :class="{
                'footer-desc-value': !isSun,
                'footer-desc-sun': isSun,
              }"
            >
              {{ teamName }}
            </span>
          </div>
        </div>
      </div>
      <!-- 未开始倒计时,模块 -->
      <Countdown
        v-else-if="activitytStatus == 1"
        :lottery="lottery"
        :isSun="isSun"
        :isDisabled="isDisabled"
        @countdownDone="countdownDone"
      ></Countdown>
      <!-- 下注,模块 -->
      <div v-else class="footer items-center">
        <!-- pk 阶段 -->
        <template
          v-if="
            isShowPK &&
            (activitytStatus == 2 ||
              activitytStatus == 7 ||
              activitytStatus == 8)
          "
        >
          <!-- 为下注展示文案--以下注展示卡片 -->
          <div
            v-if="pkCards.length <= 0"
            class="footer-top items-center footer-top-card-bg"
          >
            <img class="footer-top-img" src="/image/pledge/title-icon.svg" />
            <div class="footer-top-text">{{ $t("lotteryMoney.ljxzslpk") }}</div>
          </div>
          <div
            v-else
            class="footer-top items-center footer-top-card-bg"
            :class="{
              'footer-top-hasCards': pkCardShow.length > 0,
            }"
          >
            <div
              v-for="(item, index) in pkCardShow"
              :key="item.id"
              class="footer-top-card"
              :class="{
                'footer-top-card-animation': cardAnimationIdx == index,
              }"
              :ref="(el) => setRefAction(el, index)"
              @click="showPkPopup(item, index)"
              @animationend="animationEndFn(index)"
            >
              <template v-if="item.transactionHash">
                <img
                  class="footer-top-card-imgbg"
                  src="/image/lotterymoney/card-pkbg1-icon.png"
                />
                <div class="footer-top-card-ripple"></div>
                <div class="footer-top-card-ripple"></div>
                <div class="footer-top-card-ripple"></div>
                <div class="footer-top-card-ripple"></div>
                <div class="footer-top-card-ripple"></div>
                <img class="footer-top-card-img" :src="item.src" />
              </template>
              <div v-else>
                <img class="footer-top-card-imgslz" :src="item.src" />
                <!-- <div class="slzLoader"></div> -->
              </div>
            </div>

            <div v-if="pkCards.length > 5" class="footer-top-nums">
              {{ `X ${pkCards.length}` }}
            </div>
          </div>
        </template>
        <!-- 活动结束,展示邀请好友 -->
        <div
          v-if="isPageFiveLater && activitytStatus == 3"
          class="footer-inviteFriends items-center"
          @click="jumpPage('inviteFriendsMonery')"
        >
          <img
            class="footer-inviteFriends-close"
            src="/image/close-dark1-icon.svg"
            @click.stop="isPageFiveLater = false"
          />
          <div class="footer-inviteFriends-left items-center">
            <img
              class="footer-inviteFriends-left-img"
              src="/image/lotterymoney/inviteFriends-rightlogo-icon.svg"
            />
            <div class="footer-inviteFriends-left-info">
              <div class="footer-inviteFriends-left-info-title">
                {{ $t("inviteFriends.yqhylcj") }}
              </div>
              <div class="footer-inviteFriends-left-info-desc">
                {{ $t("inviteFriends.maxjj").split("60000")[0] }}
                <span style="color: #f29301; font-weight: 560">35,000</span>
                BDC
              </div>
            </div>
          </div>
          <div
            class="footer-inviteFriends-right"
            @click.stop="copyInviteFriendsUrl"
          >
            {{ $t("inviteFriends.qyq") }}
          </div>
        </div>
        <!-- 下注按钮 -->
        <div class="footer-bottom items-center">
          <div
            class="footer-btn-border"
            :class="{
              'footer-btn-border-disabled': isDisabled,
            }"
          >
            <div
              class="footer-btn"
              :class="{
                'footer-btn-disabled': isDisabled && !isSun,
                'footer-btn-disabled-sun': isDisabled && isSun,
                'footer-btn-sun': !isDisabled && isSun,
              }"
              @click="betClick"
            >
              {{ btnTitle }}
            </div>
          </div>
          <!-- 底部下注数量和队伍描述 -->
          <div class="footer-desc">
            {{ $t("lotteryMoney.bqyxzcs") }}
            <span
              v-if="lottery"
              :class="{
                'footer-desc-value': !isSun,
                'footer-desc-sun': isSun,
              }"
              >{{
                lottery
                  ? lottery.sessionDrawCount +
                    pageData.betPopupInfo.sessionFreeDrawCount
                  : 0
              }}</span
            >
            ，{{ $t("lotteryMoney.nddw")
            }}<span
              :class="{
                'footer-desc-value': !isSun,
                'footer-desc-sun': isSun,
              }"
            >
              {{ teamName }}
            </span>
          </div>
        </div>
      </div>
    </template>
    <!-- 免费抽奖入口 -->
    <!-- v-if="lottery" -->
    <lotteryFreeBox
      v-if="false"
      :lottery="lottery"
      @click.stop="showFreePopup"
    ></lotteryFreeBox>
    <!-- 下注弹窗: 这里的lottery判断是为了,解决在没有拿到抽奖次数的前提下,提前获取账户余额,导致无法获取正确的避险账户余额问题 -->
    <BetPopup
      v-if="lottery"
      v-model:show="pageData.isShowBetPopup"
      :detail="pageData.betPopupInfo"
      :isSun="isSun"
      @refresh="popupCall"
    ></BetPopup>
    <!-- 中奖弹窗 -->
    <WinningPopup
      v-if="lottery"
      v-model:show="pageData.isShowWinningPopup"
      :isLotteryType="isLottery"
      :isSun="isSun"
      :lotteryBonus="lotteryBonus"
      :prizesTime="lottery.beginTime"
      :teamConfigId="lottery.winner && lottery.winner.teamConfigId"
      :teamName="teamName"
      :winnerSid="lottery.winner && lottery.winner.winnerSid"
      :userName="lottery.winner && lottery.winner.nickname"
    ></WinningPopup>
    <!-- 无资格弹窗提示 -->
    <NotEligibleSundayPopup
      v-if="lottery"
      v-model:show="isEligibleSunday"
      :lottery="lottery"
      @betCall="betCall(2)"
      @inviteFriends="betCall(1)"
    ></NotEligibleSundayPopup>
    <!-- pk升级动画 -->
    <PkUpgrade v-model:show="isPkUpgrade" :lottery="lottery"></PkUpgrade>
    <!-- 一键开卡 -->
    <cardOpeningAll
      v-if="lottery"
      v-model:show="cardOpeningAllShow"
      :lottery="lottery"
      :cards="allCards"
    ></cardOpeningAll>
    <!-- 新用户福利领卡-弹窗 -->
    <userBenefitsPopup
      v-if="
        lottery &&
        lottery.newUserBonusCount &&
        Number(lottery.newUserBonusCount) > 0
      "
      v-model:show="userBenefitsPopupShow"
      :lottery="lottery"
      @confirm="userBenefitsPopupClick"
    />
    <!-- 邀请好友免费抽奖,弹窗 -->
    <userSharePopup
      v-if="lottery"
      v-model:show="userSharePopupShow"
      :lottery="lottery"
    />
    <!-- 升级弹窗 -->
    <UpdatePopup v-model:show="isUpdatePopupShow" />
  </div>
</template>
<script setup name="lotteryMoney">
import {
  getTeamInfo,
  syncServerTime,
  getLotterySimpleInfo,
  openMyCard,
  getMyCard,
} from "@/api/lottery";
import { getUserInfo } from "@/api/user";
import { getOssFileUrl, decimalToLength, throttle, debounce } from "@/utils";
import { formatToTimeZone } from "@/utils/format";
import { JUMPAPPS } from "~/config";
import { useUserStore } from "~~/store/modules/user";
import { useGlobalStore } from "~~/store/global";
import { useLotteryMoneyStore } from "~~/store/modules/lottery-money";
import {
  useEventBus,
  useDateFormat,
  useNetwork,
  useClipboard,
} from "@vueuse/core";
import BetPopup from "../../components/lotterymoney/bet-popup.vue";
import LotteryEnd from "../../components/lotterymoney/lottery-end.vue";
// import LotteryStart from "../../components/lotterymoney/lottery-start.vue";
import Countdown from "../../components/lotterymoney/countdown.vue";
import WinningPopup from "../../components/lotterymoney/winning-popup.vue";
import HashView from "../../components/lotterymoney/hashView.vue";
import Qualification from "../../components/lotterymoney/qualification.vue";
import NotEligibleSundayPopup from "../../components/lotterymoney/not-eligible-Sun-popup.vue";
import PkUpgrade from "../../components/lotterymoney/pkUpgrade.vue";
import cardOpeningAll from "../../components/lotterymoney/card-opening-all.vue";
import userBenefitsPopup from "../../components/lotterymoney/user-benefits-popup.vue";
import userSharePopup from "../../components/lotterymoney/user-share-popup.vue";
import lotteryFreeBox from "../../components/lotterymoney/lottery-free-box.vue";

import Jackpot from "../../components/lotterymoney/jackpot-prod.vue";
import { useWindowSize, usePageVisibility } from "@vant/use";
import { useSocket } from "@/utils/useWebSocket";
import * as MITO from "@zhj1214/qdjk-web";
import UpdatePopup from "../../components/lotterymoney/update-popup.vue";

/**
 * @description: webSocket + 轮询方案 完整逻辑如下
 * 轮询:
 * 1. 调用抽奖大赢家信息接口
 * 2. 调用用户 bdc 账户接口,根据 bdc 可用余额获取,避险账户信息
 * 3. 根据活动状态,以及不同的活动四个阶段,查询:下注列表(第一阶段)/卡片数量/第一名~第四名信息/
 * 4. 下注前,查询队伍信息
 * 5. 切换到后台,再次进入前台: 查询服务器时间,更新时间
 *
 * socket: 只有当天且在进行中的活动需要建立链接
 * 1. 先获取一次大赢家信息,下注列表,pk 阶段卡信息,top4 信息
 * 2. 尝试建立socket 链接
 * 3. 建立成功,在获取一次大赢家信息
 * 4. 接收消息类型: 所有人下注消息,所有人开卡消息,活动状态(结束)消息,中奖消息
 * 5. 主动调用: 下注,查询队伍,同步服务器时间,开卡
 *
 * @author: zhj1214
 */

// definePageMeta({
//   keepalive: true,
// });

const globalStore = useGlobalStore();
// 如果没有登录-直接跳转登录页面
if (!globalStore.$state.token && process.client) {
  bridge.onAppLogin();
}

const file = getOssFileUrl({
  sharePage: "/invite-friends/share",
  avatarDefault: "/image/avatar-default.png",
});

const userState = useUserStore();
const lotteryMoneyStore = useLotteryMoneyStore();

const { t } = useI18n();
const scrollEl = ref();

// firebase埋点
const firebase = useInitFirebase(); // 初始化firebase
// 抽奖信息
const lottery = ref();
// 页面属性
const pageData = reactive({
  loading: false, // 是不是下拉刷新,true 则重新获取数据
  toDayIdx: null, // 今天周几的索引
  isShowBetPopup: false, // 下注弹窗
  isShowWinningPopup: false, // 中奖
  betPopupInfo: {
    sessionId: null, // 周期 id
    periodId: null, // sessionId == periodId 代表周日
    teamsInfo: null, // 队伍信息
    teamPrizeRate: 0, // 队伍分红比例
    sessionDrawCount: 0,
    maxSessionDrawCount: 0,
    costAmount: 100, // 下注所需BDC
    isSunMoneyBet: false, // 是不是周日美金下注,逻辑
    sessionFreeDrawCount: 0, // 用户今日免费抽奖已下注总次数
  }, // 下注弹窗参数
  isRetry: false, // 是否展示重试样式
  serverTime: 0,
  lotteryPoolAmount: "", // 奖池美金数量(5 位小数)
  sessionStatus: null,
});

// 活动样式逻辑状态  0:上线前几天(没有幸运抽奖) 1 未开始  2 进行中(第一阶段,pk下注阶段)  3 已结束 4 重试状态  6 结算中 7 pk上连中 8 pk开卡中
const activitytStatus = computed((val) => {
  if (pageData.sessionStatus != null && lottery.value) {
    // 0. 活动未开始 / 下线
    if (pageData.sessionStatus == 0) {
      if (val != 0)
        console.log(
          "活动未开始 / 下线  =>  显示已结束 sessionStatus:",
          pageData.sessionStatus
        );
      return 3;
    }
    // 1. 第三,第四阶段
    if (Number(pageData.serverTime) > Number(lottery.value.pkEndTime)) {
      // pageData.sessionStatus == 3  计算中
      if (pageData.sessionStatus == 0 || pageData.sessionStatus == 5) {
        if (val != 3) {
          console.log("status:", pageData.sessionStatus, "=>", "3 活动已结束");
        }

        return 3;
      } else if (
        (pageData.sessionStatus == 3 || pageData.sessionStatus == 2) &&
        lottery.value.hashPk
      ) {
        // pkStatus hash PK 状态 0:pk进行中 1:上链中 2:开卡中 3:开卡完成
        // 兜底:当前时间 > 第四阶段倒计时
        if (
          lottery.value.hashPk &&
          Number(pageData.serverTime) >
            Number(lottery.value.hashPk.pkOpenEndTime || 0)
        ) {
          console.log(
            lottery.value.hashPk.pkOpenEndTime,
            "兜底:当前时间 > 第四阶段倒计时",
            "=>",
            "6 计算中"
          );
          return 6;
        }
        // 兜底:当前时间 > 第三阶段倒计时
        else if (
          lottery.value.hashPk.pkStatus == 2 ||
          Number(pageData.serverTime) >
            Number(lottery.value.hashPk.pkSyncEndTime || 0)
        ) {
          console.log("兜底:当前时间 > 第三阶段倒计时", "=>", "8 未开卡");
          return 8;
        } else if (lottery.value.hashPk.pkStatus == 3) {
          console.log("hashPk.pkStatus: 3", "=>", "6 计算中");
          return 6;
        } else if (lottery.value.hashPk.pkStatus == 2) {
          console.log("hashPk.pkStatus: 2", "=>", "8 未开卡");
          return 8;
        } else if (lottery.value.hashPk.pkStatus == 1) {
          console.log("hashPk.pkStatus: 1", "=>", "7 上链中");
          return 7;
        } else {
          console.log("当前时间 > 第二阶段倒计时: 未知状态", "=>", "7 上链中");
          return 7;
        }
      } else {
        console.log(pageData.sessionStatus, "未知状态", "=>", "6 计算中");
        return 6;
      }
    }
    // 2. 第一阶段没有人下注,时间不到第三阶段,直接进入第二阶段
    else if (
      !lottery.value.leader &&
      Number(pageData.serverTime) > Number(lottery.value.firstStageEndTime) &&
      Number(pageData.serverTime) <= Number(lottery.value.pkEndTime)
    ) {
      if (val != 2) console.log("活动  =>  进行中:", pageData.sessionStatus);
      return 2;
    }
    // 3. 第一阶段,倒计时结束(在获取一次抽奖信息确保没有人下单,领先者没有变的情况下,才能显示结算中)
    else if (
      lottery.value.leader &&
      Number(pageData.serverTime) >
        Number(lottery.value.leader.drawEndTime) + 3000 &&
      Number(pageData.serverTime) <= Number(lottery.value.firstStageEndTime)
    ) {
      // 1.临界点不属于-倒计时结束下注成功
      // 2. 一旦进入第二阶段,倒计时结束都不会显示:计算中了
      if (pageData.sessionStatus == 3) {
        console.log("第一阶段,倒计时+3结束,计算中", pageData.sessionStatus);
        return 6;
      } else if (pageData.sessionStatus == 0 || pageData.sessionStatus == 5) {
        console.log("第一阶段,倒计时+3,活动结束:", pageData.sessionStatus);
        return 3;
      } else {
        console.log("第一阶段,倒计时+3结束,计算中", pageData.sessionStatus);
        return 6;
      }
    } else if (pageData.sessionStatus == 1) {
      if (val != 1) console.log("活动  =>  未开始:", pageData.sessionStatus);
      return 1;
    } else if (pageData.sessionStatus == 2) {
      if (val != 2) console.log("活动  =>  进行中:", pageData.sessionStatus);
      return 2;
    } else if (pageData.sessionStatus == 3) {
      console.log("活动  =>  计算中6:", pageData.sessionStatus);
      return 6;
    } else if (pageData.sessionStatus == 0 || pageData.sessionStatus == 5) {
      if (val != 3) console.log("活动  =>  已结束:", pageData.sessionStatus);
      return 3;
    } else if (pageData.sessionStatus == 4) {
      console.log("活动  =>  请求失败 4:", pageData.sessionStatus);
      return 4;
    } else {
      console.log("活动  =>  状态未知 4:", pageData.sessionStatus);
      return 4; // 活动状态异常,冻结场景
    }
  } else {
    console.log("活动  =>  信息未知,显示结束 3:", pageData.sessionStatus);
    return 3;
  }
});

// 活动状态变更
watch(
  () => activitytStatus.value,
  (newval, oldVal) => {
    console.warn("活动状态,从", oldVal, "变更", newval);

    // 活动状态,保存到 store 中
    lotteryMoneyStore.$patch((state) => {
      state.activitytStatus = newval;
    });
    // 更新当前是第几阶段
    if (
      lottery.value &&
      lottery.value.beginTime &&
      Number(globalStore.$state.serverTime) > ckbzTime
    ) {
      if (newval == 1 || newval == 3 || newval == 4) {
        lotteryMoneyStore.$patch((state) => {
          state.drawStage = 0;
        });
      } else if (newval == 7) {
        lotteryMoneyStore.$patch((state) => {
          state.drawStage = 3;
        });
      } else if (newval == 8 || newval == 6) {
        lotteryMoneyStore.$patch((state) => {
          state.drawStage = 4;
        });
      } else if (newval == 2) {
        if (
          Number(globalStore.$state.serverTime) <
          Number(lottery.value.firstStageEndTime)
        ) {
          lotteryMoneyStore.$patch((state) => {
            state.drawStage = 1;
          });
        } else {
          lotteryMoneyStore.$patch((state) => {
            state.drawStage = 2;
          });
        }
      }
    } else {
      lotteryMoneyStore.$patch((state) => {
        state.drawStage = 0;
      });
    }
    // 如果活动结束,且 socket 在链接中,则关闭链接
    if (newval == 0 || newval == 3 || newval == 4) {
      if (status.value == "OPEN") {
        if (newval == 3) {
          // 如果还是当天,且小于第四阶段时间 + 60*60*1000, 不关闭
          if (
            lottery.value.hashPk &&
            curWeek.value &&
            curWeek.value.dayIdx == pageData.toDayIdx &&
            lottery.value.hashPk &&
            Number(pageData.serverTime) <
              Number(lottery.value.hashPk.pkOpenEndTime) + 60 * 60 * 1000
          )
            return;
        }
        console.warn("如果活动结束,且 socket 在链接中,则关闭链接");
        close && closeSocket();
      }
    }
    // 如果从未开始 => 进行中需要建立连接
    else if (
      (newval == 2 || newval == 6 || newval == 7 || newval == 8) &&
      (oldVal == 0 || oldVal == 1 || oldVal == 3 || oldVal == 4)
    ) {
      if (status.value == "CLOSED") {
        console.warn("活动从", oldVal, "=>进行中", newval, "=>尝试建立连接");
        open && openSocket();
      }
    }
    // 活动状态变更,重置邀请好友状态,计时
    if (newval != 3) {
      isPageFiveSeconds = 0;
    }
  }
);

// socket 只有当天且在进行中的活动需要建立链接
let pongTimeout = 10000;
let connectedInterval = null;
let destinations = ["destination:/topic/", "destination:/user/"]; // 订阅的消息,才能去 JSON 转换,避免失败
let isThredFail = ref(false); // 6 次重连失败
let recoveryFailedFn = () => {
  console.error("socket 6 次重连失败");
};
let onConnected = (ws) => {
  // console.log("socket 建立链接, onConnected:", ws);
  // 1. ❗️:由于vueuse封装中,没有心跳响应就会自动关闭链接,这里自行制造一条服务端的伪消息,欺骗客户端达到心态成功的目的;
  if (ws.onmessage) {
    connectedInterval = setInterval(() => {
      ws.onmessage("\n");
    }, pongTimeout - 7000); // 这里的心跳检测时间只要小于 5s,就能永远发送心跳
  }
  // 2.1 重置订阅消息数组
  isSUBSCRIBEArr.value = [];
  // 2.2 第一条建立链接的消息
  send("CONNECT\naccept-version:1.1,1.0\nheart-beat:10000,10000\n\n\x00");
};
// 错误 code: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code
let onError = (val) => {
  isContecting = false;
  isCloseIng = false;
  console.error("-socket-onError:", val);
  MITO.log({
    message: `${isPageVisibility} socket-onError:${val}`,
    tag: "抽美金页面,手动上报错误",
    level: "high",
    ex: "手动",
  });
};

// token: 由于无法增加请求头参数,message 增加,导致后端改动大,暂时放在连接中
const { open, data, status, close, send } = useSocket(
  `/bdc/lottery?token=${globalStore.$state.token}&language=${globalStore.$state.language}&Package-Id=${globalStore.$state.packageId}`,
  {
    message: "\n",
    interval: 10000,
    pongTimeout,
  },
  false, // recoveryFailedFn
  onConnected,
  onError
);

/**
 * 是否开始链接 Socket
 * 1. 是不是活动当天
 * 2. 活动是否在进行中
 * */
let isSUBSCRIBEArr = ref([]); // 作用: 1.不会重复订阅  2. 查看订阅了哪些,后面还可以防止漏掉哪些订阅
let isContecting = false; // 是否已经正在链接 socket 了
const openSocket = () => {
  return;
  if (status.value != "CLOSED")
    return console.warn("socket 不是 CLOSED 状态无需 链接🔗");
  if (isContecting) {
    console.warn("正在建立链接,请稍等..");
    return;
  }
  if (isCloseIng) return console.warn("正在关闭,不能链接 socket");
  if (!lottery.value || !pageData.toDayIdx) {
    console.warn(
      "lottery.value =",
      !!lottery.value ? "存在" : "不存在,无需建立 socket"
    );
    return;
  }
  if (curWeek.value && curWeek.value.dayIdx == pageData.toDayIdx) {
    if (activitytStatus.value != 4) {
      if (process.client) {
        if (
          lottery.value.hashPk &&
          curWeek.value &&
          curWeek.value.dayIdx == pageData.toDayIdx &&
          lottery.value.hashPk &&
          Number(pageData.serverTime) >
            Number(lottery.value.hashPk.pkOpenEndTime) + 60 * 60 * 1000
        ) {
          console.warn("活动已结束 60 分钟,无需连接 socket");
          return;
        }
        console.warn("调用 open 连接 socket");
        // isSUBSCRIBEArr.value = [];
        isContecting = true;
        open();
      }
    } else {
      console.warn("活动状态 4,无需连接 socket");
    }
  }
};

/**
 * @description: 关闭 socket
 * 1. 重置 stroe 中的状态
 */
let isCloseIng = false; // 是否正在关闭
const closeSocket = () => {
  if (process.client) {
    if (status.value != "OPEN")
      return console.warn("socket 不是 open 状态无需关闭");
    if (isCloseIng) return console.warn("正在关闭 socket");
    if (isContecting) return console.warn("正在链接,不能关闭 socket");
    console.warn("调用 close 关闭 socket");
    // isSUBSCRIBEArr.value = [];
    // 1. 发送关闭消息
    send("DISCONNECT\n\n\x00");
    // 2. 更改状态
    lotteryMoneyStore.resetPollingData();
    // 3. 关闭,保证关闭消息发送出去,在调用
    isCloseIng = true;
    setTimeout(() => {
      isContecting = false;
      close && close();
    }, 100);
  }
};

/**
 * @description: 网络断开,恢复; socket 重连逻辑
 */
const { isOnline } = useNetwork();
const isOnlineWatch = watch(
  () => isOnline.value,
  (newVal) => {
    if (!process.client) return;
    // console.warn(newVal ? "网络正常" : "网络断开");
    console.log("status.value:", status.value);

    if (!newVal) {
      console.warn("网络断开, 尝试关闭 socket");
      close && closeSocket();
    } else {
      console.warn("网络正常, status关闭, 尝试连接 socket");
      open && openSocket();
    }
  },
  {
    immediate: true,
  }
);

watch(
  () => lotteryMoneyStore.isNeedPolling,
  (newVal, oldVal) => {
    if (process.client)
      console.warn("是否可以,请求接口?", newVal ? "✅" : "❌");
  },
  {
    immediate: true,
  }
);
// 下拉刷新场景: 更新第一名数据
const top1Update = useEventBus("lotteryMoney-top1-update");
// 下注成功,刷新下注列表
const betSuccess = useEventBus("lottery-money-bet-Success");
// 状态监测处理
let tryCatchNums = 6; // 重试次数
/**
 * 0.1 是否重连:
 * 1. 活动开始前半小时 < 当前时间 < 活动第四阶段结束时间 + 1 小时
 * 2. 活动当天,不是其他日期
 * 3. 重试次数大于 0, isContecting = false
 * */
const tryCatchFn = () => {
  if (
    lottery.value &&
    curWeek.value &&
    curWeek.value.dayIdx == pageData.toDayIdx &&
    Number(pageData.serverTime) >
      Number(lottery.value.beginTime) - 30 * 60 * 1000 &&
    Number(pageData.serverTime) <
      Number(lottery.value.hashPk.pkOpenEndTime) + 60 * 60 * 1000
  ) {
    if (tryCatchNums >= 1 && !isContecting) {
      tryCatchNums -= 1;
      console.warn(
        "socket 未知场景断开链接,第",
        6 - tryCatchNums,
        "次尝试,连接 socket"
      );
      openSocket();
    }
  }
};
const socketStatusWatch = watch(
  () => status.value,
  (newVal, oldVal) => {
    console.warn("socket 状态变更,从", oldVal, "=>当前状态", newVal);

    // 调用 open 连接 socket
    // socket 状态变更,从 CLOSED =>当前状态 CONNECTING
    // vconsole.min.js:10 socket 状态变更,从 CONNECTING =>当前状态 CLOSED
    // vconsole.min.js:10 socket 状态变更,从 CLOSED =>当前状态 OPEN
    // vconsole.min.js:10 socket 状态变更,从 OPEN =>当前状态 CLOSED
    // vconsole.min.js:10 socket 状态变更,从 CLOSED =>当前状态 CONNECTING
    // socket 状态变更,从 CONNECTING =>当前状态 OPEN
    // socket 状态变更,从 CONNECTING =>当前状态 CLOSED
    // socket 状态变更,从 CLOSED =>当前状态 OPEN

    // 0. 链接断联以后,重置数据状态,重试链接
    if (newVal == "CLOSED" && oldVal == "OPEN") {
      // isSUBSCRIBEArr.value = [];
      isCloseIng = false;
      tryCatchFn();
    }
    // 0.1 链接建立失败,重试链接
    if (oldVal == "CONNECTING" && newVal == "CLOSED") {
      console.log(
        `CONNECTING => CLOSED socket-链接失败. 当前tryCatchNums:${tryCatchNums}`
      );
      // isSUBSCRIBEArr.value = [];
      isCloseIng = false;
      tryCatchFn();
    }

    // 1. 如果链接成功,重新加载一次数据,稳定性的保证
    if (newVal == "OPEN" && oldVal == "CONNECTING") {
      // isSUBSCRIBEArr.value = [];
      isContecting = false;
      console.warn("socket 连接成功,重新加载一次数据,稳定性的保证");
      // 1 更改状态,下次进入,刷新页面所有数据
      lotteryMoneyStore.resetPollingData();
      // 2. 调用接口
      top1Update.emit();
      refreshTop4.emit();
      betSuccess.emit();
      getLotterySessionInfoRequest();
      isThredFail.value = false;
    }

    // 2. 更新 socket 的链接状态
    lotteryMoneyStore.$patch((state) => {
      state.isUseSocketing = newVal == "OPEN";
    });
  },
  {
    immediate: true,
  }
);

// 消息处理
const betSocket = useEventBus("lotteryMoney-socket-bdcLotteryBetting"); // 下注通知
const openCardSocket = useEventBus("lotteryMoney-socket-bdcLotteryOpenCard"); // 开卡通知
// 字符串: a > b : 1  a == b : 0  a < b : -1
const strSpecificSize = (a, b) => {
  if (!a || !b) return false;
  if (a.length >= b.length) {
    if (a.length > b.length) {
      return 1;
    } else {
      return a > b ? 1 : -1; // 长度相等
    }
  }
  return -1;
};

const socketMsgWatch = watch(
  () => data.value,
  (newVal) => {
    // console.log("socket data:", newVal);
    if (!newVal) return;
    if (!lottery.value) return console.warn("lottery.value 不存在,消息不处理");
    if (pageData.sessionStatus == 0)
      return console.warn("pageData.sessionStatus == 0 消息不处理");
    if (curWeek.value && curWeek.value.dayIdx != pageData.toDayIdx)
      return console.warn("消息不是活动当天 tab,消息不处理");

    if (
      Number(pageData.serverTime) <
        Number(lottery.value.beginTime) - 30 * 60 * 1000 ||
      Number(pageData.serverTime) >
        Number(lottery.value.hashPk.pkOpenEndTime) + 60 * 60 * 1000
    ) {
      return console.warn("消息不在活动时间内,消息不处理");
    }

    try {
      if (typeof newVal === "string") {
        // 1. 订阅消息
        if (newVal.includes("CONNECTED\n")) {
          if (
            !isSUBSCRIBEArr.value.includes(`destination:/topic/bdc/lottery`)
          ) {
            isSUBSCRIBEArr.value.push(`destination:/topic/bdc/lottery`);
            send("SUBSCRIBE\nid:sub-0\ndestination:/topic/bdc/lottery\n\n\x00");
          }
          if (userState.$state.sid) {
            setTimeout(() => {
              if (
                !isSUBSCRIBEArr.value.includes(
                  `/user/${userState.$state.sid}/topic/bdc/lottery`
                )
              ) {
                isSUBSCRIBEArr.value.push(
                  `/user/${userState.$state.sid}/topic/bdc/lottery`
                );
                send(
                  `SUBSCRIBE\nid:sub-1\ndestination:/user/${userState.$state.sid}/topic/bdc/lottery\n\n\x00`
                );
              }
            }, 0);
          }
          return;
        }
        // 2. 订阅的消息处理
        if (
          newVal.includes(destinations[0]) ||
          newVal.includes(destinations[1])
        ) {
          let json = newVal.split("\n\n")[1];

          // console.log("socket 消息-分割 json:", json);
          // 如果 lottery 不存在,就没有办法更新数据了
          if (json && lottery.value) {
            const obj = JSON.parse(
              json
                .substring(0, json.length - 1)
                .replace(/\s/g, "")
                .replace(/\s/g, "\n")
                .replace(/\s/g, "\x00")
            );
            console.warn("socket 消息转换:", JSON.parse(JSON.stringify(obj)));

            /**
             * 下注消息
             * 1. 根据-teamConfigId + sid,更新自己的队伍
             * 2. 根据-teamConfigId + sid,更新下注次数
             * 3. 更新奖池
             * 4. 更新领先者,下注列表
             * 5. 更新第二阶段数量展示
             * */
            if (obj.messageType == "bdcLotteryBetting" && obj.data) {
              // 如果是自己下注的,且没有队伍信息的时候,更新一下自己的队伍信息
              if (obj.data.teamConfigId) {
                // 更新下注次数
                if (userState.$state.sid == obj.data.sid) {
                  // if (!pageData.betPopupInfo.sessionDrawCount) {
                  //   pageData.betPopupInfo.sessionDrawCount = 1;
                  //   lottery.value.sessionDrawCount = 1;
                  // } else {
                  //   pageData.betPopupInfo.sessionDrawCount += 1; // 已下注次数
                  //   lottery.value.sessionDrawCount += 1;
                  // }
                  // 更新一下自己的队伍信息
                  if (!lottery.value.teamConfigId) {
                    lottery.value.teamConfigId = obj.data.teamConfigId;
                    if (obj.data.teamConfigId == 1) {
                      lottery.value.teamName = t("lotteryMoney.redTeam");
                    } else if (obj.data.teamConfigId == 2) {
                      lottery.value.teamName = t("lotteryMoney.yellowTeam");
                    } else if (obj.data.teamConfigId == 3) {
                      lottery.value.teamName = t("lotteryMoney.blueTeam");
                    }
                  }
                  // 服务端,自己的队伍配置 id
                  if (!pageData.betPopupInfo.serverTeamId) {
                    pageData.betPopupInfo.serverTeamId =
                      obj.data.teamConfigId || "";
                  }
                }
              }

              // 更新奖池信息
              if (lottery.value.pool) {
                if (obj.data.pool) {
                  lottery.value.pool = obj.data.pool;
                  if (lottery.value.superPool) {
                    lottery.value.superPool.superWinnerPoolAmount =
                      obj.data.pool.superWinnerPoolAmount;
                  }

                  pageData.lotteryPoolAmount = obj.data.pool.lotteryPoolAmount; // 奖池金额
                  pageData.betPopupInfo.teamPrizeRate =
                    obj.data.pool.teamPrizeRate; // 队伍分红比例

                  if (moneyStart.value == 0 && moneyValue.value == 0) {
                    moneyStart.value = Number(
                      decimalToLength(obj.data.pool.lotteryPoolAmount)
                    );
                    moneyValue.value = Number(
                      decimalToLength(obj.data.pool.lotteryPoolAmount)
                    );
                  } else if (
                    Number(obj.data.pool.lotteryPoolAmount) > moneyValue.value
                  ) {
                    moneyValue.value = Number(
                      decimalToLength(obj.data.pool.lotteryPoolAmount)
                    );
                    setTimeout(() => {
                      moneyStart.value = Number(
                        decimalToLength(obj.data.pool.lotteryPoolAmount)
                      );
                    }, 500);
                  } else {
                    moneyValue.value = Number(
                      decimalToLength(obj.data.pool.lotteryPoolAmount)
                    );
                  }
                } else {
                  moneyValue.value = 0;
                  moneyStart.value = 0;
                  pageData.lotteryPoolAmount = 0;
                }
              }
              // 其他字段
              lottery.value.sessionTotalCostAmount =
                obj.data.sessionTotalCostAmount; // 当期下注总花费 单位:美元
              lottery.value.sessionTotalDrawCount =
                obj.data.sessionTotalDrawCount; // 当前周期所有用户总下注次数
              lottery.value.sessionUserCount = obj.data.sessionUserCount; // 参与人数
              // 第一阶段
              if (obj.data.drawStage == 1) {
                // 谁下注

                const betUser = {
                  avatar: obj.data.avatar,
                  drawTime: obj.data.drawTime,
                  nickname: obj.data.nickname,
                  id: obj.data.id,
                  sid: obj.data.sid,
                  teamName: obj.data.teamName,
                  teamConfigId: obj.data.teamConfigId,
                  drawEndTime:
                    Number(obj.data.drawTime) +
                    Number(lottery.value.firstStageDrawWaitMilli || 0),
                };

                if (obj.data.teamConfigId == 1) {
                  betUser.teamName = t("lotteryMoney.redTeam");
                } else if (obj.data.teamConfigId == 2) {
                  betUser.teamName = t("lotteryMoney.yellowTeam");
                } else if (obj.data.teamConfigId == 3) {
                  betUser.teamName = t("lotteryMoney.blueTeam");
                }

                // 更新领先者
                lottery.value.leader = betUser;
                // 通知下注列表数据更新
                betSocket.emit({
                  betUser,
                });
              }
              // 第二阶段
              if (obj.data.drawStage == 2 && lottery.value.hashPk) {
                lottery.value.hashPk.hashPkBettingCount =
                  obj.data.bettingHashPk.hashPkBettingCount;
                lottery.value.hashPk.hashPkUserCount =
                  obj.data.bettingHashPk.hashPkUserCount;
                // lottery.value.hashPk.successSyncToChainCount =
                //   obj.data.bettingHashPk.successSyncToChainCount; // 已上链订单数
                lottery.value.hashPk.pendingSyncToChainCount =
                  obj.data.bettingHashPk.pendingSyncToChainCount;
                // lottery.value.hashPk.pendingOpenCardCount =
                //   obj.data.bettingHashPk.pendingOpenCardCount; // 当期所有用户,未开卡数量
              }

              // 是否显示奖池上限提示
              if (
                !lottery.value.isReachMax &&
                Number(obj.data.lotteryPoolIncrementAmount) == 0
              ) {
                lottery.value.isReachMax = 1;
              }
            }
            // 开卡消息 1. 更新自己的排名信息 2. pk 升级,覆盖 top4  3. stroe 中国保存 top4 信息,用于更新 top4 列表,以及后面的扩展
            else if (obj.messageType == "bdcLotteryOpenCard" && obj.data) {
              // 谁在开卡
              const openCardtUser = {
                id: obj.data.id,
                sid: obj.data.sid,
                nickname: obj.data.nickname,
                avatar: obj.data.avatar,
                teamConfigId: obj.data.teamConfigId,
                teamName: obj.data.teamName,
                drawTime: obj.data.drawTime, // 下注时间
                transactionHash: obj.data.transactionHash,
                hashScore: obj.data.hashScore,
                // hashStatus: obj.data.hashStatus,
              };

              if (obj.data.teamConfigId == 1) {
                openCardtUser.teamName = t("lotteryMoney.redTeam");
              } else if (obj.data.teamConfigId == 2) {
                openCardtUser.teamName = t("lotteryMoney.yellowTeam");
              } else if (obj.data.teamConfigId == 3) {
                openCardtUser.teamName = t("lotteryMoney.blueTeam");
              }

              // pk长度变更的时候的 top4,都变了需要直接覆盖
              let top4 = [];
              // pk 长度升级,公共函数
              const updatePkLengthFn = (hashScore) => {
                if (hashScore.length > lottery.value.hashPk.hashScoreLength) {
                  lottery.value.hashPk.hashScoreLength = hashScore.length; // 更新,pk 长度
                  if (
                    !lottery.value.hashPk.hashScoreLengthChange &&
                    obj.data.openCardHashPk.hashScoreLengthChange
                  ) {
                    lottery.value.hashPk.hashScoreLengthChange =
                      obj.data.openCardHashPk.hashScoreLengthChange; // 如果没有初始值
                  }

                  if (hashScoreLengthCur.value && hashScore.length) {
                    if (hashScore.length > hashScoreLengthCur.value) {
                      nextTick(() => {
                        isPkUpgrade.value = true;
                      });
                      hashScoreLengthCur.value = hashScore.length;
                    }
                  }
                }
              };
              //
              if (obj.data.openCardHashPk) {
                if (!lottery.value.hashPk) lottery.value.hashPk = {};
                // lottery.value.hashPk.myMaxHashScore =
                //   obj.data.openCardHashPk.myMaxHashScore; // 我的得分
                // lottery.value.hashPk.myMaxHashScoreRank =
                //   obj.data.openCardHashPk.myMaxHashScoreRank; // 我的排名
                lottery.value.hashPk.pendingOpenCardCount =
                  obj.data.openCardHashPk.pendingOpenCardCount; // 当期所有用户,未开卡数量

                // 更新 top 榜单
                if (obj.data.openCardHashPk.topList) {
                  top4 = obj.data.openCardHashPk.topList.map((element) => {
                    if (element.teamConfigId == 1) {
                      element.teamName = t("lotteryMoney.redTeam");
                    } else if (element.teamConfigId == 2) {
                      element.teamName = t("lotteryMoney.yellowTeam");
                    } else if (element.teamConfigId == 3) {
                      element.teamName = t("lotteryMoney.blueTeam");
                    }
                    return element;
                  });
                  lottery.value.topHashList = obj.data.openCardHashPk.topList; // 升级动画需要用到
                }

                // 更新 pk长度
                if (obj.data.openCardHashPk.hashScoreLengthChange) {
                  if (top4 && top4.length > 0) {
                    console.log(
                      "pk位数升级变化消息-hashScoreLengthChange 0:",
                      openCardtUser.hashScore
                    );

                    updatePkLengthFn(openCardtUser.hashScore);
                  }
                }
              }
              // 维护统一的 pkTop4Arr 数据源
              if (top4.length > 0) {
                console.warn("pk升级,直接覆盖 top4 榜单");
                lotteryMoneyStore.$patch((state) => {
                  state.pkTop4Arr = top4.slice(0, 4);
                });
              } else if (
                lotteryMoneyStore.$state.pkTop4Arr &&
                lotteryMoneyStore.$state.pkTop4Arr.length >= 4
              ) {
                // 是否需要更新排名
                if (
                  strSpecificSize(
                    openCardtUser.hashScore,
                    lotteryMoneyStore.$state.pkTop4Arr[3].hashScore
                  ) == 1
                ) {
                  const arr = (lotteryMoneyStore.$state.pkTop4Arr || []).concat(
                    [openCardtUser]
                  );
                  console.log("开卡人分数 > 第四名分数, pkTop4Arr变更");
                  const arrSort = arr.sort((a, b) => {
                    if (a.hashScore == b.hashScore) {
                      return Number(a.drawTime) - Number(b.drawTime);
                    } else {
                      return strSpecificSize(a.hashScore, b.hashScore) == 1
                        ? -1
                        : 1;
                    }
                  });

                  lotteryMoneyStore.$patch((state) => {
                    state.pkTop4Arr = arrSort.slice(0, 4);
                  });
                }
                // 如果,是 pk 升级的场景,但是后端没有推送消息,就走下面的逻辑
                if (
                  strSpecificSize(
                    openCardtUser.hashScore,
                    lotteryMoneyStore.$state.pkTop4Arr[0].hashScore
                  ) == 1
                ) {
                  console.log(
                    "pk位数升级变化消息-hashScoreLengthChange 1:",
                    openCardtUser.hashScore
                  );
                  updatePkLengthFn(openCardtUser.hashScore);
                }
              }
              // 不够 4 个,加一个在排序
              else {
                const arr = (lotteryMoneyStore.$state.pkTop4Arr || []).concat([
                  openCardtUser,
                ]);
                if (
                  lotteryMoneyStore.$state.pkTop4Arr &&
                  lotteryMoneyStore.$state.pkTop4Arr.length == 0
                ) {
                  lotteryMoneyStore.$patch((state) => {
                    state.pkTop4Arr = arr.slice(0, 4);
                  });
                  console.log(
                    "pkTop4Arr 长度为 0,直接添加数据, pkTop4Arr变更",
                    lotteryMoneyStore.$state.pkTop4Arr
                  );
                } else {
                  console.log(
                    "pkTop4Arr 长度不够 < 4,添加数据+排序, pkTop4Arr变更"
                  );
                  lotteryMoneyStore.$patch((state) => {
                    const arrSort = arr.sort((a, b) => {
                      if (a.hashScore == b.hashScore) {
                        return Number(a.drawTime) - Number(b.drawTime);
                      } else {
                        return strSpecificSize(a.hashScore, b.hashScore) == 1
                          ? -1
                          : 1;
                      }
                    });
                    state.pkTop4Arr = arrSort.slice(0, 4);
                  });
                }
              }

              // 是不是自己的开卡
              // if (userState.$state.sid == openCardtUser.sid) {
              //   if (!lottery.value.hashPk.myMaxHashScore) {
              //     lottery.value.hashPk.myMaxHashScore = openCardtUser.hashScore;
              //   } else if (
              //     openCardtUser.hashScore.length >
              //     lottery.value.hashPk.myMaxHashScore.length
              //   ) {
              //     lottery.value.hashPk.myMaxHashScore = openCardtUser.hashScore;
              //   } else if (
              //     openCardtUser.hashScore.length ==
              //       lottery.value.hashPk.myMaxHashScore.length &&
              //     openCardtUser.hashScore > lottery.value.hashPk.myMaxHashScore
              //   ) {
              //     lottery.value.hashPk.myMaxHashScore = openCardtUser.hashScore;
              //   }
              // }
              openCardSocket.emit({
                openCardtUser,
                top4,
              });
            }
            // 活动状态变更消息  1. 更新活动状态  2. 活动结束信息展示  3. pk 阶段数据展示
            else if (obj.messageType == "bdcLotterySessionChange" && obj.data) {
              // 活动状态
              if (obj.data.sessionStatus != null) {
                lottery.value.sessionStatus = obj.data.sessionStatus;
                pageData.sessionStatus = obj.data.sessionStatus;
                if (!isDisabled.value) {
                  isDisabled.value =
                    obj.data.sessionStatus == 1 ||
                    obj.data.sessionStatus == 5 ||
                    obj.data.sessionStatus == 3;
                } else {
                  if (obj.data.sessionStatus == 2) {
                    if (obj.data.sessionChangeHashPk) {
                      if (obj.data.sessionChangeHashPk.pkStatus == 0) {
                        isDisabled.value = false;
                      }
                    }
                  }
                }
              }
              // 活动结束
              if (obj.data.winner) {
                lottery.value.winner = obj.data.winner;
                lottery.value.winnerNickname = obj.data.winner.nickname;
              }
              // pk 状态数据
              if (obj.data.sessionChangeHashPk) {
                if (!lottery.value.hashPk) {
                  lottery.value.hashPk = {};
                }
                lottery.value.hashPk.pkStatus =
                  obj.data.sessionChangeHashPk.pkStatus; // # hash PK 状态 0:pk进行中 1:上链中 2:开卡中 3:开卡完成
                if (obj.data.sessionChangeHashPk.pkStatus >= 2) {
                  lottery.value.hashPk.pendingSyncToChainCount = 0; // 08.30 新增的需求,到第四阶段以后写死是 0
                } else {
                  lottery.value.hashPk.pendingSyncToChainCount =
                    obj.data.sessionChangeHashPk.pendingSyncToChainCount || 0; // # 待上链数量
                }

                lottery.value.hashPk.pendingOpenCardCount =
                  obj.data.sessionChangeHashPk.pendingOpenCardCount; // # 待开卡数量

                if (obj.data.sessionChangeHashPk.pkSyncEndTime) {
                  lottery.value.hashPk.pkSyncEndTime =
                    obj.data.sessionChangeHashPk.pkSyncEndTime; // # 上链结束时间
                }

                // # 开卡结束时间
                if (obj.data.sessionChangeHashPk.pkOpenEndTime) {
                  lottery.value.hashPk.pkOpenEndTime =
                    obj.data.sessionChangeHashPk.pkOpenEndTime;
                }
              }

              // 邀请的用户获奖
              if (obj.data.inviterInfo) {
                lottery.value.inviterInfo = obj.data.inviterInfo;
              }
            }
            // 中奖消息  1. 更新活动状态  2. 活动结束信息展示  3. pk 阶段数据展示  4. 弹窗触发逻辑
            else if (obj.messageType == "bdcLotteryPrize" && obj.data) {
              if (!lottery.value.winner) lottery.value.winner = {};
              // 奖金:  winnerType 1:大赢家 2:队伍分红
              if (
                userState.$state.sid == obj.data.winnerSid &&
                obj.data.sid == obj.data.winnerSid &&
                obj.data.winnerType == 1
              ) {
                lottery.value.winner.sessionPrizeAmount = obj.data.prizeAmount;
                if (!lottery.value.winner.nickname) {
                  lottery.value.winner.nickname =
                    lottery.value.winnerNickname ||
                    lottery.value.myNickname ||
                    "--"; // 只有自己中奖才会,用到这个字段
                }
              } else {
                lottery.value.userTeamPrizeAmount = obj.data.prizeAmount || 0;
              }

              lottery.value.winner.winnerSid = obj.data.winnerSid;
              lottery.value.winner.teamConfigId = lottery.value.teamConfigId;
              // 即使大赢家,又是队伍分红,值展示大赢家
              if (obj.data.sid == obj.data.winnerSid) {
                if (!pageData.isShowWinningPopup && obj.data.winnerType == 1) {
                  isShowWinnerPopup();
                }
              } else {
                // 当前没有弹窗的情况下才能执行 isShowWinnerPopup ,不然会隐藏当前的弹窗
                if (!pageData.isShowWinningPopup && obj.data.winnerType != 1) {
                  isShowWinnerPopup();
                }
              }
            }
            // 上链成功, 服务端websocket推送message:
            else if (
              obj.messageType == "bdcLotterySyncChainSuccess" &&
              obj.data
            ) {
              // 更新界面显示的-数量
              if (obj.data.syncChainSuccessHashPk) {
                // pk 待开卡数量
                if (
                  !validatenull(
                    obj.data.syncChainSuccessHashPk.pendingOpenCardCount
                  )
                ) {
                  lottery.value.hashPk.pendingOpenCardCount =
                    obj.data.syncChainSuccessHashPk.pendingOpenCardCount;
                }
                // 上链中
                if (
                  !validatenull(
                    obj.data.syncChainSuccessHashPk.pendingSyncToChainCount
                  )
                ) {
                  // 08.30 新增的需求,到第四阶段以后写死是 0,第四阶段以后就不更新,这个数值了
                  if (lottery.value.hashPk.pkStatus < 2) {
                    lottery.value.hashPk.pendingSyncToChainCount =
                      obj.data.syncChainSuccessHashPk.pendingSyncToChainCount;
                  } else {
                    lottery.value.hashPk.pendingSyncToChainCount = 0;
                  }
                }
                // 已上链数量
                if (
                  !validatenull(
                    obj.data.syncChainSuccessHashPk.successSyncToChainCount
                  )
                ) {
                  lottery.value.hashPk.successSyncToChainCount =
                    obj.data.syncChainSuccessHashPk.successSyncToChainCount;
                }
              }
              // 如果是 pk 阶段,且是自己下注的卡,更新上链中的卡状态
              if (
                userState.$state.sid == obj.data.sid &&
                obj.data.drawStage >= 2 &&
                pkCards.value &&
                pkCards.value.length > 0
              ) {
                pkCards.value.some((e) => {
                  if (!e.transactionHash) {
                    e.id = obj.data.id;
                    e.drawTime = obj.data.drawTime;
                    e.transactionHash = obj.data.transactionHash;
                    e.hashScore = "";
                    return true;
                  }
                });
                // 去重
                pkCards.value = Array.from(
                  new Map(pkCards.value.map((item) => [item.id, item])).values()
                );
              }
            }
          }
        } else {
          console.log("❌未知订阅-消息类型 socket data:", newVal);
        }
      } else {
        console.log("❌未知消息类型 socket data:", newVal);
      }
    } catch (error) {
      console.error("socket data", error);
      MITO.log({
        message: `${isPageVisibility} socket-onError-socketMsgWatch: ${error}`,
        tag: "抽美金页面,手动上报错误",
        level: "high",
        ex: "手动",
      });
    }
  },
  {
    immediate: true,
  }
);
// 获取用户信息太慢了,导致错过了ws订阅时机,这里补偿一下
const sidWatch = watch(
  () => userState.$state.sid,
  (newVal, oldVal) => {
    if (newVal && newVal != oldVal && status.value && status.value == "OPEN") {
      if (!isSUBSCRIBEArr.value.includes(`/user/${newVal}/topic/bdc/lottery`)) {
        isSUBSCRIBEArr.value.push(`/user/${newVal}/topic/bdc/lottery`);
        send(
          `SUBSCRIBE\nid:sub-1\ndestination:/user/${newVal}/topic/bdc/lottery\n\n\x00`
        );
      }
    }
  },
  {
    immediate: true,
  }
);

// 获取 GTM+7 时间周几，返回值是0（周日）到6（周六）之间的数字, 来确定今天是周几
const weekObj = { Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6, Sun: 0 };
let day7 = ref([]);
const initDate = () => {
  // console.log("--pageData.serverTime--", pageData.serverTime);

  const { week } = formatToTimeZone(
    new Date(pageData.serverTime),
    "Asia/Jakarta",
    false
  );

  // 7 天数据
  day7.value = [
    {
      // title: "Mon",
      title: t("lotteryMoney.z1"),
      dayIdx: 1,
      isActivity: week == "Mon",
    },
    {
      // title: "Tue",
      title: t("lotteryMoney.z2"),
      dayIdx: 2,
      isActivity: week == "Tue",
    },
    {
      // title: "Wed",
      title: t("lotteryMoney.z3"),
      dayIdx: 3,
      isActivity: week == "Wed",
    },
    {
      // title: "Thu",
      title: t("lotteryMoney.z4"),
      dayIdx: 4,
      isActivity: week == "Thu",
    },
    {
      // title: "Fri",
      title: t("lotteryMoney.z5"),
      dayIdx: 5,
      isActivity: week == "Fri",
    },
    {
      // title: "Sat",
      title: t("lotteryMoney.z6"),
      dayIdx: 6,
      isActivity: week == "Sat",
    },
    {
      // title: "Sun",
      title: t("lotteryMoney.z7"),
      dayIdx: 7,
      isActivity: week == "Sun",
    },
  ];
  // 赋值 pageData.toDayIdx
  day7.value.forEach((e) => {
    if (e.isActivity) {
      pageData.toDayIdx = e.dayIdx;
    }
  });
};

// 当前是周几: 用这个字段来判断是前一天,或者后一天
const curWeek = computed(() => {
  return day7.value.find((e) => e.isActivity);
});

// 队伍名称
const teamName = computed(() => {
  if (lottery.value) {
    if (lottery.value.teamConfigId == 1) {
      return t("lotteryMoney.redTeam") || "--";
    } else if (lottery.value.teamConfigId == 2) {
      return t("lotteryMoney.yellowTeam") || "--";
    } else if (lottery.value.teamConfigId == 3) {
      return t("lotteryMoney.blueTeam") || "--";
    }
    return lottery.value.teamName || "--";
  } else {
    return "--";
  }
});

/**
 * @description: 计算当地时间,是否显示跨天
 */
const beginTimeTag = ref("");
const firstStageEndTimeTag = ref("");
const secondEndTimeTag = ref("");
const initCrossDayTime = () => {
  // 计算是不是跨天: 其他周几的情况都显示一样的.请求失败的场景暂时不考虑(不显示)
  if (
    lottery.value.beginTime &&
    !beginTimeTag.value &&
    Number(pageData.serverTime) > 1000
  ) {
    // 1. 开始时间
    const begin = useDateFormat(
      Number(lottery.value.beginTime),
      "YYYY-MM-DD"
    ).value;
    const begin_sjc = new Date(`${begin} 00:00:00`).getTime();
    // const begin_yue = useDateFormat(Number(beginTime.value), "MM").value;
    const curD = useDateFormat(pageData.serverTime, "YYYY-MM-DD").value;
    const curD_sjc = new Date(`${curD} 00:00:00`).getTime();
    // const curD_yue = useDateFormat(pageData.serverTime, "MM").value;
    const beginTag = (begin_sjc - curD_sjc) / 24 / 60 / 60 / 1000;
    beginTimeTag.value = `${Number(beginTag) > 0 ? "+" : ""}${beginTag}`;
    // console.log(begin, "本地-开始时间-当前", curD, "--");

    // 第一段 结束时间
    const endTime = useDateFormat(
      Number(lottery.value.firstStageEndTime),
      "YYYY-MM-DD"
    ).value;
    const endTime_sjc = new Date(`${endTime} 00:00:00`).getTime();
    const curDEnd = useDateFormat(pageData.serverTime, "YYYY-MM-DD").value;
    const curDEnd_sjc = new Date(`${curDEnd} 00:00:00`).getTime();
    const endTimeTag = (endTime_sjc - curDEnd_sjc) / 24 / 60 / 60 / 1000;

    firstStageEndTimeTag.value = `${
      Number(endTimeTag) > 0 ? "+" : ""
    }${endTimeTag}`;

    // 第二段 结束时间
    if (lottery.value.pkEndTime) {
      const secondEndTime = useDateFormat(
        Number(lottery.value.pkEndTime),
        "YYYY-MM-DD"
      ).value;
      const secondEndTime_sjc = new Date(`${secondEndTime} 00:00:00`).getTime();
      const curDEnd2 = useDateFormat(pageData.serverTime, "YYYY-MM-DD").value;
      const curDEnd2_sjc = new Date(`${curDEnd2} 00:00:00`).getTime();
      const secondEndTimeTags =
        (secondEndTime_sjc - curDEnd2_sjc) / 24 / 60 / 60 / 1000;

      secondEndTimeTag.value = `${
        Number(secondEndTimeTags) > 0 ? "+" : ""
      }${endTimeTag}`;
    }
  }
};

// 是不是周日
const isSun = computed(() => {
  if (pageData.toDayIdx == 7) {
    return true;
  } else if (lottery.value) {
    return lottery.value.sessionId == lottery.value.periodId;
  }
  return false;
});

// 周日-是否有资格下注: 1. 累计下注次数不足 5 住; 2. 周日没有邀请好友 registerInviteUserCount
const isEligibilityZr = computed(() => {
  // return true;
  // 周期 id 相等代表是超级大赢家
  if (lottery.value && lottery.value.sessionId == lottery.value.periodId) {
    // if (
    //   Number(lottery.value.superPool.currentPeriodDrawCount) >=
    //   Number(lottery.value.superPool.currentPeriodSupperDrawCount)
    // ) {
    //   return true;
    // }
    // 0 不可以使用 bdc 下注  1. 可以
    return (
      lottery.value.superPool.currentPeriodBdcDrawEnable == 1 ||
      (lottery.value.registerInviteUserCount &&
        lottery.value.registerInviteUserCount >= 1)
    );
  }
  return true;
});

// 自己是不是中奖了: 0 没有中奖  1 大赢家得主  2 队伍分红
const isLottery = ref(0);
// 奖金
const lotteryBonus = ref(0);
// 是否展示-中奖弹窗: 只在中奖当天,活动结束时间~当天 23 点 59 分 59 秒展示一次
const isShowWinnerPopup = () => {
  // pageData.isShowWinningPopup = true;
  // return
  // 1. 是否中奖
  if (
    userState.$state.sid &&
    lottery.value.winner &&
    userState.$state.sid == lottery.value.winner.sid
  ) {
    isLottery.value = 1;
  } else if (
    lottery.value.winner &&
    lottery.value.winner.teamConfigId == lottery.value.teamConfigId
  ) {
    isLottery.value = 2;
  } else {
    isLottery.value = 0;
  }

  //  2. 奖金
  if (isLottery.value && isLottery.value > 0) {
    if (isLottery.value == 2) {
      lotteryBonus.value = lottery.value.userTeamPrizeAmount;
    } else {
      lotteryBonus.value = lottery.value.winner.sessionPrizeAmount;
    }
  }
  // 3. 只弹出一次: 只在中奖当天,活动结束时间~当天 23 点 59 分 59 秒展示一次,往期不展示
  if (isLottery.value != 0) {
    // 3.1 展示弹窗,当前这一期活动才展示
    if (curWeek.value && curWeek.value.dayIdx == pageData.toDayIdx) {
      const lotterySessionId = localStorage.getItem(
        userState.$state.sid + "-" + "lotterySessionId"
      );
      if (!lotterySessionId) {
        pageData.isShowWinningPopup = true;
        // 3.2 期数 id - 缓存
        localStorage.setItem(
          userState.$state.sid + "-" + "lotterySessionId",
          lottery.value.sessionId
        );
      } else if (lottery.value.sessionId != lotterySessionId) {
        // 有可能是 0, 0 则不展示
        if (Number(lotteryBonus.value) > 0) {
          pageData.isShowWinningPopup = true;
          // 3.2 期数 id - 缓存
          localStorage.setItem(
            userState.$state.sid + "-" + "lotterySessionId",
            lottery.value.sessionId
          );
        }
      } else {
        pageData.isShowWinningPopup = false;
      }
    }
  } else {
    pageData.isShowWinningPopup = false;
  }
};

// 获取当天早上 xx 点的时间戳
function getTodayMorningTimestamp(date, hour = 0, min = 0, se = 0, ms = 0) {
  // 获取当前日期
  const now = date || new Date();
  // 创建一个新的 Date 对象，设置为当天的早上 10 点
  const todayMorning = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
    hour,
    min,
    se,
    ms
  );
  // 获取时间戳
  return todayMorning.getTime();
}
// pk上级
const isPkUpgrade = ref(false);
const hashScoreLengthCur = ref(1); // 当前长度

// 一键开卡
const cardOpeningAllShow = ref(false);
// 新用户福利,领卡弹窗
const userBenefitsPopupShow = ref(false);
const userBenefitsPopupClick = (val) => {
  // 1. 隐藏弹窗
  userBenefitsPopupShow.value = false;
  // 2. 免费次数赋值
  lottery.value.freeDrawCount = val;
  pageData.betPopupInfo.freeDrawCount = val; // 免费可用次数
  // 3. 重置新人免费次数
  lottery.value.newUserBonusCount = 0;
};
// 邀请好友免费抽奖
const userSharePopupShow = ref(false);
const showFreePopup = () => {
  userSharePopupShow.value = true;
};

const allCards = ref([]);
// 奖池滚动
const moneyStart = ref(0);
const moneyValue = ref(0);
const isDisabled = ref(false);

// 查询抽奖信息

const getLotterySessionInfoRequest = async (
  isFirst = false,
  isLoading = false
) => {
  // 1. 是否需要 loadding
  // if (isLoading) {
  //   showLoadingToast({
  //     message: `${t("common.requestIng")}...`,
  //     forbidClick: true,
  //     duration: 15000,
  //   });
  // }
  // 2. 请求
  let selectId = 1;
  try {
    selectId =
      !pageData.toDayIdx && curWeek.value
        ? curWeek.value.dayIdx
        : day7.value[pageData.toDayIdx - 1].dayIdx;
  } catch (error) {
    if (curWeek.value && curWeek.value.dayIdx) {
      selectId = curWeek.value.dayIdx;
    } else {
      // 防止请求失败
      const weekObj = {
        Mon: 1,
        Tue: 2,
        Wed: 3,
        Thu: 4,
        Fri: 5,
        Sat: 6,
        Sun: 0,
      };
      const { week } = formatToTimeZone(
        pageData.serverTime && Number(pageData.serverTime) > 100000
          ? new Date(pageData.serverTime)
          : new Date(),
        "Asia/Jakarta",
        false
      );
      let dayIndex = weekObj[week];
      if (dayIndex == 0) dayIndex = 7;
      selectId = dayIndex;
    }
  }

  // let res = await getLotterySessionInfo({
  //   selectId: selectId,
  // });

  let res = {
    sessionId: 240930,
    periodId: selectId == 7 ? 240930 : 241006,
    sessionStatus: 2,

    beginTime: 1727697600000,
    firstStageEndTime: 1727697600000,
    pkEndTime: 1727701200000 + 10000 * 24 * 60 * 60 * 1000,
    firstStageDrawWaitMilli: "300000",
    costAmount: "100",
    sessionDrawCount: 0,
    sessionFreeDrawCount: 0,
    teamConfigId: null,
    teamName: null,
    userTeamPrizeAmount: null,
    maxSessionDrawCount: 10000,
    sessionUserCount: 0,
    sessionTotalDrawCount: 0,
    sessionTotalCostAmount: null,
    pool: {
      lotteryPoolAmount: "0",
      sessionPrizeRate: "0.3",
      moveToNextSessionPrizeRate: "0.1",
      teamPrizeRate: "0.2",
      moveToSupperWinnerPrizeRate: "0.4",
      sessionPrizeAmount: "0",
      moveToNextSessionPrizeAmount: "0",
      teamPrizeAmount: "0",
      moveToSupperWinnerPrizeAmount: "0",
    },
    superPool: {
      currentPeriodDrawCount: 0,
      currentPeriodBdcDrawEnable: 0,
      currentPeriodSupperDrawCount: 5,
      superWinnerPoolAmount: "0",
    },
    leader: null,
    winner: null,
    recentDrawRecordList: null,
    hashPk: {
      hashPkBettingCount: 0,
      hashPkUserCount: 0,
      pendingSyncToChainCount: 0,
      successSyncToChainCount: 0,
      pkStatus: 0,
      pendingOpenCardCount: 0,
      pkSyncEndTime: 1727701500000 + 10000 * 24 * 60 * 60 * 1000,
      pkOpenEndTime: 1727701800000 + 10000 * 24 * 60 * 60 * 1000,
      hashScoreLength: 1,
    },
    topHashList: [],
    myNickname: "",
    maxBdcIncrementAmount: "1000",
    reachMaxBdcIncrementAmountLimit: null,
    inviteCode: null,
    inviterInfo: null,
    freeDrawCount: 0,
    newUserBonusCount: 0,
    registerInviteUserCount: 0,
  };
  // console.log("--res--", res);

  // closeToast();
  // 3.第一次请求就失败,才展示
  if (!res) {
    isThredFail.value = true;
    return;
  }

  if (res) {
    if (isThredFail.value) isThredFail.value = false;
    /******** start zhjdebugger start ********/
    // res.hashPk = null;
    // res.pool = null;
    // res.superPool = null;
    // 周日
    // res.periodId = res.sessionId;
    // res.sessionStatus = 2;
    // res.winner = {
    //   winType: 1,
    //   transactionHash: "sdadmlasds5545dasd",
    // };
    // res.beginTime = new Date("2024/09/27 17:06").getTime();
    // res.firstStageEndTime = new Date("2024/09/27 17:06").getTime();
    // res.pkEndTime = new Date("2024/09/26 21:20").getTime();
    //
    // res.hashPk = {
    //   pendingOpenCardCount: 0,
    //   pkStatus: 0,
    //   pkSyncEndTime: new Date("2024/09/26 22:21").getTime(), // 上链结束时间
    //   pkOpenEndTime: new Date("2024/09/26 22:48").getTime(), // 开卡结束时间
    // };
    // res.freeDrawCount = 1; // 免费次数
    // res.newUserBonusCount = 5; // 新人可领取
    // res.registerInviteUserCount = 1; // 今天成功邀请的好友数量
    /******** end zhjdebugger end ********/

    //  抽奖信息接口查询,成功
    if (!lotteryMoneyStore.$state.isDoneLotteryInfo) {
      lotteryMoneyStore.$patch((state) => {
        state.isDoneLotteryInfo = state.isUseSocketing && true;
        state.pkTop4Arr = res.topHashList; // 保存 top 榜单
      });
    }

    // 4. 这个请求的信息是不是已过期(有的请求延迟返回,导致数据展示错误)
    // if (pageData.toDayIdx) {
    //   const { week } = formatToTimeZone(
    //     new Date(Number(res.beginTime)),
    //     "Asia/Jakarta",
    //     false
    //   );
    //   let dayIndex = weekObj[week];
    //   if (dayIndex == 0) dayIndex = 7;
    //   if (dayIndex != pageData.toDayIdx) return;
    // }

    console.warn(
      "活动开始时间:",
      useDateFormat(Number(res.beginTime), "YYYY-MM-DD HH:mm:ss").value
    );
    console.warn(
      "第一阶段-结束-时间:",
      useDateFormat(Number(res.firstStageEndTime), "YYYY-MM-DD HH:mm:ss").value
    );
    console.warn(
      "第二阶段-结束-时间:",
      useDateFormat(Number(res.pkEndTime), "YYYY-MM-DD HH:mm:ss").value
    );
    if (res.hashPk && res.hashPk.pkSyncEndTime) {
      console.warn(
        "第三阶段-结束-时间:",
        useDateFormat(Number(res.hashPk.pkSyncEndTime), "YYYY-MM-DD HH:mm:ss")
          .value
      );
      console.warn(
        "第四阶段-结束-时间:",
        useDateFormat(Number(res.hashPk.pkOpenEndTime), "YYYY-MM-DD HH:mm:ss")
          .value
      );
    }

    // 5. 赋值逻辑
    pageData.sessionStatus = res.sessionStatus;
    if (!isDisabled.value) {
      isDisabled.value =
        res.sessionStatus == 0 ||
        res.sessionStatus == 1 ||
        res.sessionStatus == 5 ||
        res.sessionStatus == 3;
    } else {
      // 调用接口,后端无法保证立刻更改状态
      // if (res.sessionStatus == 2 && res.hashPk.pkStatus == 0) {
      //   isDisabled.value = false;
      // }
    }
    lottery.value = res;

    // 是否显示奖池上限提示
    if (res.reachMaxBdcIncrementAmountLimit == 1) {
      lottery.value.isReachMax = 1;
    }
    if (res.pool) {
      pageData.lotteryPoolAmount = res.pool.lotteryPoolAmount;
      pageData.betPopupInfo.teamPrizeRate = res.pool.teamPrizeRate; // 队伍分红比例

      if (moneyStart.value == 0 && moneyValue.value == 0) {
        moneyStart.value = Number(decimalToLength(res.pool.lotteryPoolAmount));
        moneyValue.value = Number(decimalToLength(res.pool.lotteryPoolAmount));
      } else if (Number(res.pool.lotteryPoolAmount) > moneyValue.value) {
        moneyValue.value = Number(decimalToLength(res.pool.lotteryPoolAmount));
        setTimeout(() => {
          moneyStart.value = Number(
            decimalToLength(res.pool.lotteryPoolAmount)
          );
        }, 500);
      } else {
        moneyValue.value = Number(decimalToLength(res.pool.lotteryPoolAmount));
      }
    } else {
      moneyValue.value = 0;
      moneyStart.value = 0;
      pageData.lotteryPoolAmount = 0;
    }

    pageData.betPopupInfo.sessionId = res.sessionId; // 周期 id
    pageData.betPopupInfo.periodId = res.periodId; // 周期 id
    pageData.betPopupInfo.serverTeamId = res.teamConfigId || ""; // 服务端队伍配置 id
    pageData.betPopupInfo.sessionDrawCount = res.sessionDrawCount; // 已下注次数
    pageData.betPopupInfo.maxSessionDrawCount = res.maxSessionDrawCount; // 上限
    pageData.betPopupInfo.costAmount = res.costAmount; // 下注花费
    pageData.betPopupInfo.freeDrawCount = res.freeDrawCount; // 免费可用次数
    pageData.betPopupInfo.registerInviteUserCount = res.registerInviteUserCount; // 邀请好友
    pageData.betPopupInfo.sessionFreeDrawCount = res.sessionFreeDrawCount; // 用户今日免费抽奖已下注总次数

    // 5.1 是否中奖
    // if (!pageData.isShowWinningPopup) {
    //   isShowWinnerPopup();
    // }

    // 6. 活动时间变化,计算跨天时间
    // if (res.beginTime && beginTimeTag.value == "") {
    //   initCrossDayTime();
    // }
  }
  return Promise.resolve();
};

// 队伍信息
const getTeamInfoRequest = (val) => {
  showLoadingToast({
    message: `${t("common.requestIng")}...`,
    forbidClick: true,
    duration: 15000,
    zIndex: 999999999,
  });
  return getTeamInfo({ sessionId: val }).then((res) => {
    if (res) {
      pageData.betPopupInfo.teamsInfo =
        res.teamList.map((e) => {
          let file = {};
          if (e.teamConfigId == 1) {
            file = getOssFileUrl({
              bottomLeftUrl: "/image/lotterymoney/betpopup-redz-icon.svg",
              bottomRightUrl: "/image/lotterymoney/betpopup-redy-icon.svg",
              rwicon: "/image/lotterymoney/betpopup-redrw-icon.svg",
            });
            e.teamName = t("lotteryMoney.redTeam");
          } else if (e.teamConfigId == 2) {
            file = getOssFileUrl({
              bottomLeftUrl: "/image/lotterymoney/betpopup-hdz-icon.svg",
              bottomRightUrl: "/image/lotterymoney/betpopup-hdy-icon.svg",
              rwicon: "/image/lotterymoney/betpopup-hdrw-icon.svg",
            });
            e.teamName = t("lotteryMoney.yellowTeam");
          } else {
            file = getOssFileUrl({
              bottomLeftUrl: "/image/lotterymoney/betpopup-ldz-icon.svg",
              bottomRightUrl: "/image/lotterymoney/betpopup-ldy-icon.svg",
              rwicon: "/image/lotterymoney/betpopup-ldrw-icon.svg",
            });
            e.teamName = t("lotteryMoney.blueTeam");
          }
          e.bottomLeftUrl = file.bottomLeftUrl;
          e.bottomRightUrl = file.bottomRightUrl;
          e.rwicon = file.rwicon;
          return e;
        }) || [];
    }
  });
};

/**
 * @description: 同步服务器时间
 */
const syncServerTimeFn = async () => {
  const res = await syncServerTime();
  if (
    res &&
    res.nowMilli &&
    Number(res.nowMilli) > Number(pageData.serverTime)
  ) {
    pageData.serverTime = Number(res.nowMilli);
  }
};

/**
 * @description: 页面刷新请求
 */
const onRefreshRequest = () => {
  try {
    console.warn("下拉刷新了");
    // 1 更改状态,下次进入,刷新页面所有数据
    lotteryMoneyStore.resetPollingData();
    // 2. 调用接口
    pageData.loading = true;
    top1Update.emit();
    refreshTop4.emit();
    betSuccess.emit();
    const a = getLotterySessionInfoRequest();
    Promise.all([a]).finally(() => {
      pageData.loading = false;
    });
    // 3. 动画回调失败的,兜底
    isContinueRequest = true;
  } catch (error) {
    pageData.loading = false;
  }
};

/**
 * 点击重试
 * 1. 请求失败
 * 2. socket 6 次链接失败
 * */
const refreshClick = debounce(
  () => {
    if (!isThredFail.value) {
      // 1 更改状态,下次进入,刷新页面所有数据
      lotteryMoneyStore.resetPollingData();
      // 2. 调用接口
      top1Update.emit();
      refreshTop4.emit();
      betSuccess.emit();
      getLotterySessionInfoRequest(false, true);
    }
    if (
      lottery.value &&
      status.value == "CLOSED" &&
      curWeek.value.dayIdx == pageData.toDayIdx &&
      Number(pageData.serverTime) >
        Number(lottery.value.beginTime) - 30 * 60 * 1000 &&
      Number(pageData.serverTime) <
        Number(lottery.value.pkOpenEndTime) + 1 * 60 * 1000
    ) {
      if (!isContecting) {
        console.warn("活动数据加载失败,或者,socket3次链接失败,尝试建立socket");
        openSocket();
      }
    }
  },
  1000,
  false
);

/**
 * @description: 初始化定时器: 方便其他地方统一修改数据
 * 1. 时间进度逻辑实现
 */
// 创建一个特定时间的 Date 对象; 用于解决serverTime 初始值小于 1000 的场景
const ckbzTime = new Date("2024/01/01").getTime();
// 定时器-通知
const moneyInterval = useEventBus("lottery-money-interval-emit");
let trySockets = 6; // 这里也,最多重试 6 次,不行就提示

let isPageFiveSeconds = 0; // 5 秒
const isPageFiveLater = ref(false); // 进入页面 5 秒以后; 是否展示结束以后的邀请好友
const moneyIntervalTime = watch(
  () => globalStore.$state.serverTime,
  (newValue, oldValue) => {
    // console.log(newValue, "--moneyIntervalTime--", oldValue);
    if (newValue > ckbzTime) {
      // 1. 赋值
      pageData.serverTime = newValue;
      // 2. 拿到服务器时间初始化
      if (day7.value.length == 0) {
        // 2 初始化时间
        initDate();
        // 3. 获取抽奖信息,计算跨天时间
        getLotterySessionInfoRequest(true);
      }
      return;
      // 3. 变更通知
      moneyInterval.emit(newValue);
      // 4. 延时关闭 socket(当天活动结束,延迟 1 分钟关闭) 为了接收中奖消息推送
      if (
        lottery.value &&
        lottery.value.hashPk &&
        status.value == "OPEN" &&
        curWeek.value.dayIdx == pageData.toDayIdx &&
        Number(pageData.serverTime) >
          Number(lottery.value.hashPk.pkOpenEndTime) + 60 * 60 * 1000
      ) {
        console.warn("当前时间大于 ,活动结束+ 60 分钟,尝试关闭 socket");
        closeSocket();
      }
      // 5. 当前tab 是活动当天,且活动未开始,建立 socket 链接
      if (
        lottery.value &&
        status.value == "CLOSED" &&
        curWeek.value &&
        curWeek.value.dayIdx == pageData.toDayIdx &&
        Number(pageData.serverTime) >
          Number(lottery.value.beginTime) - 30 * 60 * 1000 &&
        Number(pageData.serverTime) < Number(lottery.value.beginTime)
      ) {
        if (trySockets >= 1 && !isContecting) {
          trySockets -= 1;
          console.warn(
            "tab是活动当天,且距离活动开始不到 30 分钟,尝试建立socket"
          );
          openSocket();
        }
      }
      // 6. 邀请好友,结束以后五秒,逻辑
      if (
        lottery.value &&
        activitytStatus.value == 3 &&
        curWeek.value &&
        curWeek.value.dayIdx == pageData.toDayIdx &&
        isPageFiveSeconds < 5 &&
        lotteryMoneyStore.$state.isShowInviteLottery
      ) {
        isPageFiveSeconds += 1;
        if (isPageFiveSeconds == 5 && !isPageFiveLater.value) {
          isPageFiveLater.value = true;
        }
      }
      // 7. 是否展示,新用户免费弹窗
      if (
        lottery.value &&
        lottery.value.newUserBonusCount &&
        Number(lottery.value.newUserBonusCount) > 0
      ) {
        // 使用Date构造函数直接创建表示当天0点的日期对象并获取时间戳
        let timestamp = new Date(new Date().setHours(0, 0, 0, 0)).getTime();
        if (
          pageData.serverTime > timestamp &&
          pageData.serverTime < Number(lottery.value.pkEndTime) &&
          !userBenefitsPopupShow.value
        ) {
          userBenefitsPopupShow.value = true;
        }
      }
    }
  },
  {
    immediate: true,
  }
);

watch(
  () => isSUBSCRIBEArr.value,
  (newVal) => {
    console.log(
      useDateFormat(Date.now(), "YYYY-MM-DD HH:mm:ss").value,
      "订阅了哪些消息:",
      newVal
    );
  }
);
/**
 * @description: 主页面定时任务
 * 1. 按钮状态
 * 2. 抽奖信息获取
 * 3. 抽奖卡片获取
 */
let isBreak = false; // 切换日期,是否还需要继续请求
let moneyIntervalEmit = null;
const every3Seconds = () => {
  if (!moneyIntervalEmit) {
    moneyIntervalEmit = moneyInterval.on((val) => {
      // 0. 每秒更新按钮状态
      btnStatusChange(val);

      // 0.1 检查是不是漏掉了订阅
      if ((val % 3000 > 2000 || val % 3000 == 0) && !isBreak) {
        if (
          activitytStatus.value == 2 ||
          activitytStatus.value == 6 ||
          activitytStatus.value == 7 ||
          activitytStatus.value == 8
        ) {
          if (status.value == "OPEN" && isSUBSCRIBEArr.value.length != 2) {
            if (
              !isSUBSCRIBEArr.value.includes(`destination:/topic/bdc/lottery`)
            ) {
              isSUBSCRIBEArr.value.push(`destination:/topic/bdc/lottery`);
              send &&
                send(
                  "SUBSCRIBE\nid:sub-0\ndestination:/topic/bdc/lottery\n\n\x00"
                );
            }

            if (
              userState.$state.sid &&
              !isSUBSCRIBEArr.value.includes(
                `/user/${userState.$state.sid}/topic/bdc/lottery`
              )
            ) {
              isSUBSCRIBEArr.value.push(
                `/user/${userState.$state.sid}/topic/bdc/lottery`
              );
              send(
                `SUBSCRIBE\nid:sub-1\ndestination:/user/${userState.$state.sid}/topic/bdc/lottery\n\n\x00`
              );
            } else {
              // 重新获取用户信息,在订阅
              getUserInfo().then((res) => {
                if (res && res.code === 200 && res.data?.user) {
                  userState.$state = res.data.user;
                  if (status.value == "OPEN") {
                    if (
                      !isSUBSCRIBEArr.value.includes(
                        `/user/${res.data.user.sid}/topic/bdc/lottery`
                      )
                    ) {
                      isSUBSCRIBEArr.value.push(
                        `/user/${res.data.user.sid}/topic/bdc/lottery`
                      );
                      send(
                        `SUBSCRIBE\nid:sub-1\ndestination:/user/${res.data.user.sid}/topic/bdc/lottery\n\n\x00`
                      );
                    }
                  }
                }
              });
            }
          }
        }
      }
    });
  }
};

// 页面可见状态(当前页面是否进入后台) https://vant-contrib.gitee.io/vant/#/zh-CN/use-page-visibility
const pageVisibility = usePageVisibility();
let isPageVisibility = "visible"; // 默认是可见状态
const stopWatch = watch(pageVisibility, (value) => {
  // console.log("从后台进入前台: 刷新数据 ", value);
  // 1. 记录当前状态
  isPageVisibility = value;
  // 2. 进入后台
  if (value == "visible") {
    console.warn("从后台进入前台");
    // 2.1 更改状态,下次进入,刷新页面所有数据
    lotteryMoneyStore.resetPollingData();
    // 2.2 请求数据
    syncServerTimeFn();
    getLotterySessionInfoRequest(false, true);
    top1Update.emit();
    refreshTop4.emit();
    betSuccess.emit();
    // 2.3 是否重新链接 socket
    if (
      lottery.value &&
      status.value == "CLOSED" &&
      curWeek.value &&
      curWeek.value.dayIdx == pageData.toDayIdx &&
      Number(pageData.serverTime) >
        Number(lottery.value.beginTime) - 30 * 60 * 1000 &&
      Number(pageData.serverTime) <
        Number(lottery.value.hashPk.pkOpenEndTime) + 60 * 60 * 1000
    ) {
      console.warn("进入前台以后, status关闭, 尝试连接 socket");
      openSocket();
    }
    // 2.4 是否重新获取pk 卡
    if (
      curWeek.value &&
      curWeek.value.dayIdx == pageData.toDayIdx &&
      isShowPK.value
    ) {
      getPkCards();
    }
  }
  // 3. 进入前台
  else {
    console.warn("此刻,从前台进入后台:", Date.now());
    // 隐藏一键开卡弹窗,不然重新查卡以后,就重复开卡了
    cardOpeningAllShow.value = false;
  }
});

// 是否展示-hask 环节内容 PK
let isRequestPkcards = false;
const isShowPK = computed(() => {
  if (
    lottery.value &&
    lottery.value.firstStageEndTime &&
    pageData.serverTime > Number(lottery.value.firstStageEndTime) &&
    (activitytStatus.value == 2 ||
      activitytStatus.value == 7 ||
      activitytStatus.value == 8)
  ) {
    if (pkCards.value && pkCards.value.length == 0 && !isRequestPkcards) {
      isRequestPkcards = true;
      getPkCards();
    }
    return true;
  } else {
    return false;
  }
});

const isUpdatePopupShow = ref(false);
onMounted(async () => {
  // 1. 埋点
  firebase?.logEvent("BDC_H5_LotteryMoney_PUV");
  // 2. 轮询:第一个版本,每间隔 3 秒.请求一次最新数据
  every3Seconds();
  //
  isUpdatePopupShow.value = true;
});

onBeforeUnmount(() => {
  // 0. 重置 store 状态
  lotteryMoneyStore.resetData();
  // 1.注销通知
  moneyInterval.reset();
  moneyIntervalEmit && moneyIntervalEmit();
  // 2. 删除定时器
  moneyIntervalTime && moneyIntervalTime();
  stopWatch && stopWatch();
  isOnlineWatch && isOnlineWatch();
  socketMsgWatch && socketMsgWatch();
  socketStatusWatch && socketStatusWatch();
  connectedInterval && clearInterval(connectedInterval);
  sidWatch && sidWatch();
  // 3. 关闭 socket
  if (status.value == "OPEN") {
    console.warn("页面销毁,关闭 socket");
    closeSocket();
  }
});

// 切换日期
const changeDay = throttle(
  (val) => {
    console.warn("切换日期:", val);
    // 1. 切换,请求数据
    // pkStatus.value = 0;
    pageData.toDayIdx = val;
    getLotterySessionInfoRequest(false, true).then(() => {
      nextTick(() => {
        // 1.1 滚动到顶部
        scrollEl.value.scrollTo({
          top: 0,
          behavior: "smooth",
        });
      });
    });
    // 2. 重新初始化定时器
    if (day7.value[pageData.toDayIdx - 1].isActivity) {
      isBreak = false;
    } else {
      isBreak = true;
    }
    // 3. 重置卡片数量
    isRequestPkcards = false;
    pkCards.value = [];
    // 4. 重置奖池金额
    moneyStart.value = 0;
    moneyValue.value = 0;
    // 5. 切换到别的日期需要重置一下状态,如果不是当天,还需要关闭 socket
    if (curWeek.value && curWeek.value.dayIdx != val) {
      console.warn("日期切换,关闭 socket");
      closeSocket();
    }
    // 6. 动画回调失败的,兜底
    isContinueRequest = true;
  },
  300,
  true
);

// 倒计时结束/pk动画结束
// const countdownEnds = () => {
//   console.timeEnd("pk动画时长");
//   isContinueRequest = true;
//   // 刷新整个页面
//   getLotterySessionInfoRequest();
// };

// 未开始倒计时结束
const countdownDone = () => {
  console.warn("未开始倒计时结束");
  getLotterySessionInfoRequest();

  // 1. 是否重新链接 socket
  if (
    lottery.value &&
    status.value == "CLOSED" &&
    curWeek.value &&
    curWeek.value.dayIdx == pageData.toDayIdx &&
    Number(pageData.serverTime) >
      Number(lottery.value.beginTime) - 30 * 60 * 1000 &&
    Number(pageData.serverTime) <
      Number(lottery.value.hashPk.pkOpenEndTime) + 60 * 60 * 1000
  ) {
    console.warn("未开始倒计时结束,socket没有建立链接, 尝试连接 socket");
    // 1.1 更改状态,下次进入,刷新页面所有数据
    lotteryMoneyStore.resetPollingData();
    // 1.2 请求数据
    syncServerTimeFn();
    getLotterySessionInfoRequest(false, true);
    top1Update.emit();
    refreshTop4.emit();
    betSuccess.emit();
    // 1.3 链接 socket
    openSocket();
  }
  // 变更活动状态=>进行中:这里不能这么写,有很多字段都是 null
  else {
    // lottery.value.sessionStatus = 2;
    // pageData.sessionStatus = 2;
    // if (isDisabled.value) {
    //   isDisabled.value = false;
    // }
  }
};

// 复制邀请好友链接
const copyInviteFriendsUrl = () => {
  if (!lotteryMoneyStore.$state.inviteLotteryCode) return;
  const { copy, isSupported } = useClipboard({
    source: "",
  });
  if (!isSupported.value) {
    showToast({
      message: t("mvp.other.bzcjtb"),
      "z-index": 9999999,
    });
  } else {
    const u =
      file.sharePage +
      "?hiddenBar=1" +
      `&language=${globalStore.$state.language}` +
      `&packageId=${globalStore.$state.packageId}` +
      `&code=${lotteryMoneyStore.$state.inviteLotteryCode || ""}`;

    copy(u);
    showToast({
      message: t("mvp.other.fzcg"),
      "z-index": 9999999,
    });
  }
};
// 页面跳转
const jumpPage = async (type, isApp = false) => {
  if (isApp) {
    if (type === "taskCenter") {
      firebase?.logEvent("BDC_H5_Mining_TaskCenter_Click"); // 埋点访问
      bridge.jumpAppRoute(JUMPAPPS()[type]);
    }
  } else if (type === "lotteryDesc") {
    firebase?.logEvent("BDC_H5_LotteryMoney_Desc_PUV"); // 埋点访问
    await navigateI18nTo({ path: "/lottery-money/desc" });
  } else if (type === "bdcToMoney") {
    firebase?.logEvent("BDC_H5_LotteryMoney_BDCToMoney_Click"); // 埋点访问
    await navigateI18nTo({ path: "/lottery-money/bdc-to-money" });
  } else if (type == "recordBet") {
    if (!lottery.value.sessionId) return;
    navigateI18nTo({
      path: "/lottery-money/record-bet",
      query: {
        hashScoreLength: lottery.value.hashPk
          ? lottery.value.hashPk.hashScoreLength
          : 6,
        sessionId: lottery.value.sessionId,
        beginTime: lottery.value.beginTime,
        lotteryPoolAmount: lottery.value.pool
          ? lottery.value.pool.lotteryPoolAmount || 0
          : 0,
        sessionUserCount: lottery.value.sessionUserCount,
        sessionTotalDrawCount: lottery.value.sessionTotalDrawCount,
      },
    });
  } else if (type == "previousDraws") {
    firebase?.logEvent("BDC_H5_previousDraws_PUV");
    navigateI18nTo({
      path: "/lottery-money/previous-draws-record",
      query: {
        sessionId: lottery.value.sessionId,
      },
    });
  } else if (type == "myBetRecord") {
    firebase?.logEvent("BDC_H5_myBetRecord_PUV");
    navigateI18nTo({
      path: "/lottery-money/my-bet-record",
      query: {
        sessionId: lottery.value.sessionId,
      },
    });
  } else if (type === "inviteFriendsMonery") {
    firebase?.logEvent("BDC_H5_LotteryMoney_inviteFriendsMonery_Click");
    await navigateI18nTo({ path: "/invite-friends" });
  }
};

/****************** PK 卡 ******************/
const pkCards = ref([]);
const pkCardShow = computed(() => {
  if (pkCards) {
    return pkCards.value.slice(0, 5).map((e) => {
      if (e.transactionHash) {
        e.src = getOssFileUrl({
          src: "/image/lotterymoney/card-pk0-icon.png",
        }).src;
      } else {
        e.src = getOssFileUrl({
          src: "/image/lotterymoney/bottom-pkslz-card.svg",
        }).src;
      }

      return e;
    });
  }
  return [];
});

// 上链成功的数组
const pkCardSuccess = computed(() => {
  if (pkCards.value) {
    return pkCards.value.filter((e) => {
      return !!e.transactionHash;
    });
  }
  return [];
});

// 获取卡片数量
const getPkCards = () => {
  // zhjdebugger
  // const res = {
  //   pendingSyncToChainCount: 2,
  //   pendingOpenList: [
  //     {
  //       id: 1,
  //       drawTime: Date.now(),
  //       transactionHash: "261261586411dsasdasdasfasdfasdcasd",
  //       hashScore: 98521576,
  //     },
  //     {
  //       id: 2,
  //       drawTime: Date.now(),
  //       transactionHash: "261261586411dsasdasdasfasdfasdcasd",
  //       hashScore: 98521576,
  //     },
  //     {
  //       id: 3,
  //       drawTime: Date.now(),
  //       transactionHash: "261261586411dsasdasdasfasdfasdcasd",
  //       hashScore: 98521576,
  //     },
  //     {
  //       id: 4,
  //       drawTime: Date.now(),
  //       transactionHash: "",
  //       hashScore: 98521576,
  //     },
  //   ],
  // };
  // pkCards.value = res.pendingOpenList;
  // return;
  getMyCard().then((res) => {
    if (res) {
      let slzs = [];
      if (res.pendingSyncToChainCount && res.pendingSyncToChainCount > 0) {
        slzs = Array.from({ length: res.pendingSyncToChainCount }).map(
          (el, index) => {
            return {
              id: res.pendingOpenList.length + index,
              drawTime: Date.now(),
              transactionHash: "",
              hashScore: 0,
            };
          }
        );
      }
      pkCards.value = res.pendingOpenList.concat(slzs);
    }
  });
};
// 动画结束,删除当前点击的卡片
const firstOpenCardEnd = useEventBus("lottery-opencard-first-start/end"); // 第一段动画开始/结束
const refreshTop4 = useEventBus("lottery-money-refresh-top4"); // 刷新 top4
const animationEndFn = (index, b) => {
  console.timeEnd("cardfly第一段动画结束");
  // 0. 重置索引, 1. 避免后获取卡片列表以后,后面的卡片继续做动画 2. 卡片 3 秒轮询一次,早点重置避免出现问题
  setTimeout(() => {
    cardAnimationIdx.value = -1;
    pkCards.value.splice(index, 1);
  }, 500);

  // 2. 第二段动画-放大缩小
  setTimeout(() => {
    // pkCards.value.splice(index, 1);
    firstOpenCardEnd.emit(pkCardInfo.value);
  }, 450);
};
// 第二段动画结束的回调: 开卡完成,自己不是第一名
let isContinueRequest = true;
const animationendSecond = (val) => {
  isContinueRequest = true;
  if (val == 1) {
    console.log("第一名更新,动画完成");
  } else {
    getPkCards();
  }
};
//将循环ref放入到数组中
const cardRefs = ref([]);
const cardRefPositions = ref([]);
const setRefAction = (el, index) => {
  cardRefs.value[index] = el;
  nextTick(() => {
    if (process.client) setRefActionPosition();
  });
};
// 列表渲染以后: 获取每一个元素的具体位置
const setRefActionPosition = () => {
  cardRefPositions.value = cardRefs.value.map((el) => {
    if (el) {
      const rect = el.getBoundingClientRect();
      const scrollLeft =
        window.pageXOffset || document.documentElement.scrollLeft;
      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop;

      return {
        y: rect.y + scrollTop,
        x: rect.x + scrollLeft,
        width: rect.width,
        height: rect.height,
      };
    } else {
      return {};
    }
  });
};
// 展示 PK弹窗
const { width, height } = process.client
  ? useWindowSize()
  : { width: ref(320), height: ref(667) };
const cardAnimationIdx = ref(-1); // 要做动画的卡片索引
const pkCardInfo = ref({}); // 卡片信息
const card_y = ref(0); // 卡片位置
const hashViewPosition = ref({
  x: 0,
  y: 0,
});
const endPositionY = computed(() => {
  if (hashViewPosition.value && hashViewPosition.value.y) {
    return `${hashViewPosition.value.y - card_y.value - 32}px`; // 32 适当的偏移量
  }
  return `-${card_y.value}px`;
});
const endPositionX = computed(() => {
  if (hashViewPosition.value && hashViewPosition.value.x) {
    return `${hashViewPosition.value.x - 14}px`; // 16 是头像的一半宽度
  }
  return `-${width.value / 2}px`;
});
const card_x = ref(0); // 卡片位置 x
const startPositionX = computed(() => {
  return `${card_x.value}px`;
});
// 第二/三/四 阶段 pk 交互动画,锚点的位置
const hashViewRef = ref();
// 获取窗口宽度和高度
const showPkPopup = debounce(
  async (val, index) => {
    // 0. 上连中的跳过
    if (!val.transactionHash) return;
    // 0. 上一次动画是否结束
    if (!isContinueRequest) return;

    // 1. 获取锚点的位置
    if (hashViewRef && hashViewRef.value) {
      let rect = null;
      rect = hashViewRef.value.getBoundingClientRect();
      console.log(height.value * 0.2, "--结束的锚点:", rect);

      if (rect.y && rect.y < height.value * 0.2) {
        scrollEl.value.scrollTo({
          top: height.value * 0.2,
        });
        rect = hashViewRef.value.getBoundingClientRect();
        // 滚动合适位置在做动画
        hashViewPosition.value.y = rect.y - 15;
        hashViewPosition.value.x = rect.x;
      } else if (rect.y != hashViewPosition.value.y) {
        hashViewPosition.value.y = rect.y - 15;
        hashViewPosition.value.x = rect.x;
      }
    }

    // 1.1 卡片,Y位置
    if (cardRefPositions.value && cardRefPositions.value.length > 0) {
      const clickCard = cardRefPositions.value[index];
      if (clickCard) {
        // const cpRect = cardRefs.value[index].getBoundingClientRect();
        card_y.value = clickCard.y;
        card_x.value = clickCard.x;
      }
      console.log("--开始--的位置:", card_x.value, "--", card_y.value);
    }

    // 1.1 开始动画 zhjdebugger
    // isContinueRequest = false;
    // pkCardInfo.value = {
    //   grade: "ff99",
    //   rank: 1, // 999 表示大于 100
    //   hash: "fad53fad53fad53fad53fad53fad53fad53fad53",
    // };
    // cardAnimationIdx.value = index;
    // if (pkCardInfo.value.rank == 1) {
    //   firstOpenCardEnd.emit(1);
    // }
    // return;

    // 2. 请求开卡
    if (!val.transactionHash) {
      showToast(t("lotteryMoney.slzalert"));
      return;
    }
    showLoadingToast({
      message: `${t("common.requestIng")}...`,
      forbidClick: true,
      duration: 15000,
    });
    isContinueRequest = false;
    try {
      const res = await openMyCard({ id: val.id });
      if (res) {
        // 2.1 获取,并保存,第一名信息
        if (res.hashScoreRank == 1) {
          firstOpenCardEnd.emit(1);
        }
        // 2.2 赋值状态,并展示弹窗
        pkCardInfo.value = {
          grade: `${res.hashScore || val.hashScore}`,
          rank: res.hashScoreRank ? res.hashScoreRank : 999, // 999 表示大于 100
          hash: val.transactionHash,
        };
        openCardSocket.emit({
          openCardtUser: {
            id: val.id,
            sid: userState.$state.sid,
            transactionHash: val.transactionHash,
            avatar: userState.$state.avatar || file.avatarDefault,
            teamConfigId: lottery.value.teamConfigId,
            nickname: lottery.value.myNickname,
            hashScore: `${res.hashScore || val.hashScore}`,
            rank: res.hashScoreRank ? res.hashScoreRank : 999, // 999 表示大于 100
          },
        });
        // 2.3 开始动画
        console.time("cardfly第一段动画结束");
        console.time("pk动画时长");
        // nextTick 是为了解决,页面滚动后,结束位置不准确问题
        nextTick(() => {
          cardAnimationIdx.value = index;
        });
      }
      // 请求失败,可以继续点击卡片
      else {
        isContinueRequest = true;
      }
    } catch (error) {
      console.error("开卡失败:", error);
    }
  },
  200,
  true
);

/****************** 下注按钮 ******************/

// 按钮状态更新
const btnStatusChange = (time) => {
  if (time && lottery.value) {
    if (Number(time) < Number(lottery.value.beginTime)) {
      isDisabled.value = true;
    } else if (activitytStatus.value != 2) {
      if (isShowPK.value && pkCardSuccess.value.length > 1) {
        isDisabled.value = false;
      } else {
        isDisabled.value = true;
      }
    } else {
      isDisabled.value = false;
    }
  }
  // else {
  //   isDisabled.value = true; // 避免一开始就是禁用状态
  // }
};

// 下注按钮文案
const btnTitle = computed(() => {
  if (activitytStatus.value == 1) {
    return t("lotteryMoney.wks");
  } else if (activitytStatus.value == 2) {
    if (lottery && lottery.value.freeDrawCount) {
      return t("lotteryMoney.mfxzcs").replace("x", lottery.value.freeDrawCount);
    } else {
      return t("lotteryMoney.ljxz");
    }
  } else if (activitytStatus.value == 3) {
    return t("lotteryMoney.yjs");
  } else if (activitytStatus.value == 7) {
    if (isShowPK.value && pkCardSuccess.value.length > 1) {
      return t("lotteryMoney.yjkk");
    } else {
      return t("lotteryMoney.xzjspk");
    }
  } else if (activitytStatus.value == 8) {
    if (isShowPK.value && pkCardSuccess.value.length > 1) {
      return t("lotteryMoney.yjkk");
    } else {
      return t("lotteryMoney.xzjspk");
    }
  } else if (activitytStatus.value == 6) {
    return t("lotteryMoney.yjs");
  } else if (isShowPK.value) {
    return t("lotteryMoney.xzpk");
  } else {
    return t("lotteryMoney.yjs");
  }
});

/**
 * @description: 下注按钮
 */
const isEligibleSunday = ref(false); // 无资格参加周日活动
let costAmountOne_t = false; // 下注花费只请求一次
/**
 * @description: 无资格:弹窗回调
 * @param {*} val 1 邀请好友  2 美金下注
 */
const betCall = (val) => {
  isEligibleSunday.value = false;
  if (val == 1) {
    jumpPage("inviteFriendsMonery");
  } else {
    nextTick(() => {
      console.log("无资格:弹窗回调");
      // 1. 展示下注弹窗
      // 1.1 获取下注 bdc 和账户余额,以及-已下注次数
      getLotterySimpleInfo({ sessionId: lottery.value.sessionId }).then(
        (res) => {
          if (res) {
            costAmountOne_t = true;
            // 更新
            userState.$patch((state) => {
              state.freeAmount = res.freeAmount;
            });
            pageData.betPopupInfo.sessionDrawCount = res.sessionDrawCount; // 已下注次数
            pageData.betPopupInfo.costAmount = res.costAmount; // 下注花费
            lottery.value.sessionDrawCount = res.sessionDrawCount;
            lottery.value.costAmount = res.costAmount;
          }
        }
      );
      // 1.2. 是否选择过队伍
      if (!lottery.value.teamName) {
        getTeamInfoRequest(lottery.value.sessionId).then(() => {
          nextTick(() => {
            pageData.betPopupInfo.isSunMoneyBet = true;
            pageData.isShowBetPopup = true;
          });
        });
      } else {
        pageData.betPopupInfo.isSunMoneyBet = true;
        pageData.isShowBetPopup = true;
      }
    });
  }
};

const betClick = debounce(
  () => {
    if (!isContinueRequest) return;
    if (activitytStatus.value == 2) {
      // 0. 活动最后一秒-或者-倒计时结束校验
      if (
        Number(pageData.serverTime) >=
        Number(lottery.value.pkEndTime || lottery.value.firstStageEndTime)
      ) {
        showToast({
          message: t("lotteryMoney.hdyjs"),
          forbidClick: true,
        });
        return;
      }

      // 1. 是不是周日 - 下注
      if (!isEligibilityZr.value) {
        const curDay = useDateFormat(Date.now(), "YYYY-MM-DD").value;
        const zgday = localStorage.getItem(
          userState.$state.sid + "-" + "lottery-isEligibleSunday-money-bet"
        );
        if (!zgday) {
          isEligibleSunday.value = true;
          return;
        } else {
          if (zgday != curDay) {
            isEligibleSunday.value = true;
            return;
          } else {
            if (!pageData.betPopupInfo.isSunMoneyBet) {
              pageData.betPopupInfo.isSunMoneyBet = true;
            }
          }
        }
      }

      // 2. 获取下注 bdc 和账户余额,以及-已下注次数
      if (!costAmountOne_t) {
        getLotterySimpleInfo({ sessionId: lottery.value.sessionId }).then(
          (res) => {
            if (res) {
              costAmountOne_t = true;
              // 更新
              userState.$patch((state) => {
                state.freeAmount = res.freeAmount;
              });
              pageData.betPopupInfo.sessionDrawCount = res.sessionDrawCount; // 已下注次数
              pageData.betPopupInfo.costAmount = res.costAmount; // 下注花费
              lottery.value.sessionDrawCount = res.sessionDrawCount;
              lottery.value.costAmount = res.costAmount;
            }
          }
        );
      }

      // 3. 是否选择过队伍
      if (!lottery.value.teamName) {
        getTeamInfoRequest(lottery.value.sessionId).then(() => {
          nextTick(() => {
            pageData.isShowBetPopup = true;
          });
        });
      } else {
        // 一键开卡
        // if (isShowPK.value && pkCardSuccess.value.length > 1) {
        //   console.log("一键开卡");
        //   // 取出 8 张卡
        //   allCards.value = pkCardSuccess.value.slice(0, 8);
        //   // 原数据删除 这 8 张卡
        //   const allCardsIds = allCards.value.map((e) => e.id);
        //   pkCards.value = pkCards.value.filter((e) => {
        //     return !allCardsIds.includes(e.id);
        //   });
        //   // 展示弹窗
        //   cardOpeningAllShow.value = true;
        //   return;
        // } else
        pageData.isShowBetPopup = true;
      }
    } else if (activitytStatus.value == 7) {
      // 一键开卡
      if (isShowPK.value && pkCardSuccess.value.length > 1) {
        console.log("一键开卡");
        // 取出 8 张卡
        allCards.value = pkCardSuccess.value.slice(0, 8);
        // 原数据删除 这 8 张卡
        const allCardsIds = allCards.value.map((e) => e.id);
        pkCards.value = pkCards.value.filter((e) => {
          return !allCardsIds.includes(e.id);
        });
        // 展示弹窗
        cardOpeningAllShow.value = true;
        return;
      }
    } else if (activitytStatus.value == 8) {
      // 一键开卡
      if (isShowPK.value && pkCardSuccess.value.length > 1) {
        console.log("一键开卡");
        // 取出 8 张卡
        allCards.value = pkCardSuccess.value.slice(0, 8);
        // 原数据删除 这 8 张卡
        const allCardsIds = allCards.value.map((e) => e.id);
        pkCards.value = pkCards.value.filter((e) => {
          return !allCardsIds.includes(e.id);
        });
        // 展示弹窗
        cardOpeningAllShow.value = true;
        return;
      }
    } else if (activitytStatus.value == 3) {
      showToast(t("lotteryMoney.hdyjs"));
    } else if (activitytStatus.value == 4) {
      showToast({
        message: t("lotteryMoney.jszqsd"),
        forbidClick: true,
      });
    } else if (activitytStatus.value == 1) {
      showToast(t("lotteryMoney.hdwks"));
    } else if (activitytStatus.value == 6) {
      showToast({
        message: t("lotteryMoney.hdyjs"),
        forbidClick: true,
      });
    } else {
      showToast(t("lotteryMoney.hdyjs"));
    }
  },
  500,
  false
);

/**
 * @description: 下注弹窗回调
 * @param {*} type  1. 成功 2.失败 3.去充值 4.账户被冻结(异常) 5.本期下注次数已达上限 6.避险账户状态异常
 */
const popupCall = ({
  type,
  freeDrawCount,
  successCount,
  sessionFreeDrawCount,
  costType,
}) => {
  if (type == 1) {
    // 下注成功,下注数量+1, 并且提示下了几注;
    if (successCount && successCount > 1) {
      showToast(
        t("lotteryMoney.xzcg") +
          t("lotteryMoney.xxzs").replace("xx", successCount)
      );
    } else {
      showToast(t("lotteryMoney.xzcg"));
    }
    // 下注花费类型 costType 1:BDC 2:美元 3:免费抽奖
    if (costType != 3) {
      pageData.betPopupInfo.sessionDrawCount += successCount || 0; // 已下注次数
      lottery.value.sessionDrawCount += successCount || 0;
    }

    // 清除队伍信息,防止在展示选择队伍步骤
    pageData.betPopupInfo.teamsInfo = null;
    // 是否需要更新,界面信息
    if (status.value != "OPEN") getLotterySessionInfoRequest();
    // 如果是 pk 阶段,更新一下卡数量
    if (isShowPK.value) getPkCards();
    // 周日 + 无资格美金下注. 只弹出一次
    if (isSun.value && !isEligibilityZr.value) {
      const curDay = useDateFormat(Date.now(), "YYYY-MM-DD").value;
      localStorage.setItem(
        userState.$state.sid + "-" + "lottery-isEligibleSunday-money-bet",
        curDay
      );
    }
    // 免费次数
    if (!validatenull(freeDrawCount)) {
      lottery.value.freeDrawCount = freeDrawCount;
      pageData.betPopupInfo.freeDrawCount = freeDrawCount; // 免费可用次数
      pageData.betPopupInfo.sessionFreeDrawCount = sessionFreeDrawCount; // 用户今日免费抽奖已下注总次数
    }
  }
  // 请求失败,或者超时,请重试
  else if (type == 2) {
    showToast({
      message: t("lotteryMoney.xzsbqcs"),
      forbidClick: true,
    });
  }
  // 去充值
  else if (type == 3) {
    // 桥接跳转到避险账户,目前安卓正在开发,暂时跳转到tabbar我的
    firebase?.logEvent("BDC_H5_lotteryMoney_Click_HedgeAccount");
    const hedgingWallet = JUMPAPPS()["hedgingWallet"]();
    bridge.jumpAppRoute(hedgingWallet.routeKey, isAndroid.value, hedgingWallet);
  }
  // BDC 账户异常
  else if (type == 4) {
    showToast({
      message: t("lotteryMoney.bdczhyc"),
      forbidClick: true,
    });
  }
  // 本期下注次数已达上限
  else if (type == 5) {
    showToast({
      message: t("lotteryMoney.bqxzcsydsx"),
      forbidClick: true,
    });
  }
  // 避险账户状态异常
  else if (type == 6) {
    showToast({
      message: t("lotteryMoney.bxzhyc"),
      forbidClick: true,
    });
  }
  // 激活避险账户
  else if (type == 7) {
    // 激活-避险账户
    firebase?.logEvent("BDC_H5_lottery_Click_HedgeAccount_jh");
    const hedgeAccount = JUMPAPPS()["hedgeAccount"]();
    bridge.jumpAppRoute(hedgeAccount.routeKey, isAndroid.value, hedgeAccount);
  }
  // 避险账户接口异常,获取失败,重新进入这个页面
  else if (type == 8) {
    showToast({
      message: t("common.wlycqcxjr"),
      forbidClick: true,
    });
  }
  // 下注失败,刷新页面数据
  else if (type == 9) {
    // 2.1 更改状态,下次进入,刷新页面所有数据
    lotteryMoneyStore.resetPollingData();
    // 2.2 请求数据
    getLotterySessionInfoRequest(false, true);
    top1Update.emit();
    refreshTop4.emit();
    betSuccess.emit();
  }
};

/**
 * @description: 返回上一级
 */
const handleBack = () => {
  if (!window.history.state.back) {
    navigateI18nTo({
      path: "/activity",
    });
  } else {
    navigateBack(-1);
  }
};
</script>
<style lang="scss" scoped>
.lotteryMoney {
  position: relative;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;
  will-change: scroll-position;
  padding-bottom: calc(var(--safe-area-inset-bottom) + 165px);
  background: #f0f3fa;

  &-bottom {
    padding-bottom: calc(var(--safe-area-inset-bottom) + 145 * 2px);
    // margin-bottom: 70 * 2px;
    &-max {
      padding-bottom: calc(var(--safe-area-inset-bottom) + 160 * 2px);
      // margin-bottom: 85 * 2px !important;
    }
  }
  &-bg {
    position: absolute;
    top: 0;
    left: 0px;
    width: 100vw;
    height: 434 * 2px;
  }
  &-wait {
    position: relative;
    padding: 4 * 2px 15 * 2px;
    z-index: 9;
    background: rgba(0, 123, 255, 0.2);
    backdrop-filter: blur(12px);
    justify-content: space-between;
    &-sun {
      background: rgba(255, 184, 0, 0.2);
    }
    &-icon {
      width: 18 * 2px;
      height: 18 * 2px;
    }
    &-text {
      color: #007bff;
      font-size: 13 * 2px;
      &-sun {
        color: #f29401;
      }
    }
    &-btn {
      width: 22 * 2px;
      height: 22 * 2px;
    }
  }
}
.content {
  position: relative;
}
.m_lr {
  margin: 0 15 * 2px;
}
.titleView {
  position: relative;
  z-index: 1;
  justify-content: space-between;
  margin-bottom: 8 * 2px;
  padding-top: 8 * 2px;
  &-left {
    color: #2e3649;
    font-size: 15 * 2px;
    font-weight: 700;
  }
  &-title {
    color: #141924;
    font-size: 22 * 2px;
    font-weight: 700;
  }
  &-right {
    width: 18 * 2px;
  }
}
.date {
  position: relative;
  z-index: 1;
  width: calc(100% - 15 * 4px);
  border-radius: 12 * 2px 12 * 2px 0 0;
  margin: 12 * 2px 15 * 2px 0 15 * 2px;
  background-color: #fff;
  &-item {
    width: 14.2857%;
    height: 34 * 2px;
    color: #002853;
    font-size: 13 * 2px;
    font-weight: 500;
    text-align: center;
    justify-content: center;
    &-sub {
      border-right: 1px solid rgba(115, 119, 128, 0.15);
      stroke-width: 1px;
      // height: 18 * 2px;
      width: 100%;
      padding: 0 * 2px 5 * 2px;
      &-jh {
        background: rgba(0, 123, 255, 0.12);
        border-radius: 100px;
        font-weight: 590;
        font-size: 13 * 2px;
        &-sun {
          background: rgba(255, 122, 0, 0.12);
        }
      }
      &-sun {
        border: none;
      }
    }
    &-cur {
      color: #007bff !important;
      font-size: 15 * 2px;
      font-weight: 500 !important;

      &-sun {
        color: #ff7a00 !important;
      }
    }
    &-jh {
      color: #fff !important;
      width: 16.1vw !important;
      font-size: 15 * 2px !important;
      font-weight: 700 !important;
      border-radius: 12 * 2px 0px 0px 0px;
      background: linear-gradient(90deg, #007bff 0.07%, #00b2ff 99.93%);

      &-sun {
        border-radius: 0px 12 * 2px 0px 0px !important;
        background: linear-gradient(82deg, #ffb800 6.08%, #ff4040 93.92%);
      }
    }
    &-sun {
      position: relative;
      border: none;
      font-size: 13 * 2px;
      font-weight: 510;
      color: #ff7a00;
      &-tag {
        position: absolute;
        color: rgb(255, 184, 0);
        top: -22px;
        left: 50%;
        transform: translateX(-50%);
      }
    }
  }
}

.jumps {
  padding: 10 * 2px;
  border-radius: 12 * 2px;
  background: #fff;
  width: calc(100% - 15 * 4px);
  margin: 0 15 * 2px;
  flex-direction: column;

  &-lr {
    width: 100%;
    margin: 0;
  }
  &-top {
    justify-content: space-between;
    width: 100%;
  }
  &-item {
    justify-content: center;
    flex-direction: column;
    min-width: 105 * 2px;
    &-img {
      width: 44 * 2px;
      height: 44 * 2px;
      margin-bottom: 5 * 2px;
    }
    &-btn {
      color: #141924;
      font-size: 11 * 2px;
    }
  }
}
.jackpot {
  &-left {
    position: absolute;
    z-index: 9;
    top: 47 * 2px;
    left: 0px;
    padding: 1 * 2px 15 * 2px;
    border-radius: 0px 100px 100px 0px;
    overflow: hidden;
    border: 2px solid rgba(255, 255, 255, 0.4);
    background: rgba(255, 255, 255, 0.4);
    backdrop-filter: blur(20px);
    justify-content: center;
    box-shadow: 8px 8px 32px 0px rgba(0, 0, 0, 0.1);
    &-icon {
      width: 24 * 2px;
      height: 24 * 2px;
    }
    &-fail {
      top: 77 * 2px;
    }
  }
  &-right {
    position: absolute;
    z-index: 9;
    top: 47 * 2px;
    right: 0 * 2px;
    padding: 1 * 2px 15 * 2px;
    border-radius: 100px 0px 0 100px;
    overflow: hidden;
    border: 2px solid rgba(255, 255, 255, 0.4);
    background: rgba(255, 255, 255, 0.4);
    backdrop-filter: blur(20px);
    justify-content: center;
    box-shadow: -8px 8px 32px 0px rgba(0, 0, 0, 0.1);
    &-icon {
      width: 24 * 2px;
      height: 24 * 2px;
    }
    &-fail {
      top: 77 * 2px;
    }
  }
}
.footer {
  position: fixed;
  flex-direction: column;
  z-index: 99;
  bottom: 0;
  padding-bottom: var(--safe-area-inset-bottom);
  border-radius: 16 * 2px 16 * 2px 0 0;
  background-color: #fff;
  border-top: 1px solid rgba(115, 119, 128, 0.15);

  &-top {
    width: 100%;
    padding: 0 12 * 2px 10 * 2px 12 * 2px;
    border: 1px solid rgba(255, 255, 255, 0.6);
    box-shadow: drop-shadow(0px -12px 20px rgba(0, 0, 0, 0.06));
    backdrop-filter: blur(20 * 2px) brightness(103%);
    &-hasCards {
      padding-top: 0;
      padding-bottom: 0;
    }
    &-img {
      width: 9 * 2px;
      height: 9 * 2px;
      margin-right: 5 * 2px;
    }
    &-text {
      color: #002853;
      font-size: 12 * 2px;
      line-height: 16 * 2px;
    }
    &-card {
      position: relative;
      z-index: 5;
      margin-right: 8 * 2px;
      border-radius: 4 * 2px;
      overflow: hidden;
      background: linear-gradient(180deg, #ff9b01 0.32%, #fabb1d 99.68%);
      transform-origin: center;
      min-width: 56 * 2px;
      max-width: 56 * 2px;
      min-height: 68 * 2px;
      &-bg {
        position: relative;
        z-index: 5;
        bottom: -10 * 2px;
        justify-content: center;
      }
      &-imgbg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 9;
      }

      &-imgslz {
        position: absolute;
        width: 100%;
        height: 100%;
      }

      &-img {
        position: absolute;
        z-index: 5;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        width: 30 * 2px;
        height: 40 * 2px;
        @keyframes fluctuation1 {
          0% {
            transform: translate(-50%, -50%);
          }
          100% {
            transform: translate(-50%, -60%);
          }
        }
        animation: fluctuation1 0.4s linear infinite alternate;
      }
      &-ripple {
        @keyframes ripple {
          0% {
            transform: scale(1);
            opacity: 0;
          }
          10% {
            transform: scale(1);
            opacity: 0.8;
          }
          100% {
            transform: scale(2.2);
            opacity: 0;
          }
        }
        position: absolute;
        left: 23%;
        top: 17%;
        border-radius: 45%;
        width: 30 * 2px;
        height: 40 * 2px;
        border: 0.75px solid #fff19f;
        animation: ripple 1.8s infinite;
        opacity: 0;
      }
      &-ripple:nth-child(2) {
        animation-delay: 0.2s;
      }
      &-ripple:nth-child(3) {
        animation-delay: 0.6s;
      }
      &-ripple:nth-child(4) {
        animation-delay: 0.9s;
      }
      &-ripple:nth-child(5) {
        animation-delay: 1.3s;
      }
      &-animation {
        @keyframes cardfly {
          0% {
            transform: translateY(0);
            left: v-bind("startPositionX");
          }
          100% {
            left: v-bind("endPositionX");
            transform: translateY(v-bind("endPositionY"));
          }
        }
        @keyframes shrink {
          0% {
            transform: translate(0, v-bind("endPositionY")) scale(1);
          }
          30% {
            transform: translate(0, v-bind("endPositionY")) scale(1.1);
            opacity: 1;
          }
          100% {
            transform: translate(0, v-bind("endPositionY")) scale(0);
            opacity: 0;
          }
        }

        position: absolute;
        z-index: 9999;
        // 先移动,再缩小;0.5s 代表延迟 0.5 秒等第一段动画完成,在执行第二段动画
        animation: cardfly 0.3s ease-in-out forwards,
          shrink 0.6s ease-in-out 0.3s forwards;
      }
    }
    &-nums {
      color: #002853;
      font-size: 12 * 2px;
      font-weight: 590;
    }
  }
  &-bottom {
    position: relative;
    z-index: 9;
    padding: 9 * 2px 15 * 2px 0 15 * 2px;
    flex-direction: column;
    width: 100vw;
    // min-height: 78 * 2px;
    justify-content: center;
    border-top: 1px solid rgba(255, 255, 255, 0.6);
    background-color: #fff;
  }
  &-desc {
    margin-top: 6 * 2px;
    color: #999da7;
    font-size: 12 * 2px;
    &-value {
      color: #007bff;
    }
    &-sun {
      color: #ffb800;
    }
  }

  &-btn {
    width: 100%;
    border: 0.8px solid #002853;
    background: linear-gradient(90deg, #007bff 0.34%, #00b2ff 100%);
    padding: 10 * 2px 0;
    text-align: center;
    border-radius: 6 * 2px;
    color: #fff2b2;
    font-size: 17 * 2px;
    font-weight: 700;
    border-radius: 100px;
    white-space: nowrap;
    &-sun {
      background: linear-gradient(89deg, #ff9b01 0.47%, #fabb1d 99.53%);
    }
    &-border {
      width: 100%;
      border: 0.8px solid #002853;
      padding: 2 * 2px;
      background-color: #fff2b2;
      border-radius: 100px;

      &-disabled {
        background-color: #f9f6ec;
      }
    }

    &-disabled {
      background: #bcd7f4 !important;
      color: #fff;
      &-sun {
        color: #fff;
        background: #f1dfb2 !important;
      }
    }
  }

  &-inviteFriends {
    border-radius: 12 * 2px 12 * 2px 0px 0px;
    overflow: hidden;
    justify-content: space-between;
    padding: 8 * 2px 15 * 2px;
    width: 100%;
    background: linear-gradient(
      180deg,
      rgba(255, 255, 255, 0.8) 0%,
      rgba(175, 231, 241, 0.8) 50.2%,
      rgba(189, 223, 255, 0.8) 100%
    );
    box-shadow: 0px -4px 24px 0px rgba(0, 0, 0, 0.08);
    backdrop-filter: blur(10px);
    position: relative;
    &-close {
      position: absolute;
      top: 1 * 2px;
      right: 15 * 2px;
      width: 20 * 2px;
    }
    &-left {
      flex: 1;
      &-img {
        width: 60 * 2px;
        height: 60 * 2px;
        margin-right: 8 * 2px;
      }
      &-info {
        flex: 1;
        &-title {
          color: #002853;
          font-size: 13 * 2px;
          font-weight: 590;
          margin-bottom: 8 * 2px;
        }
        &-desc {
          color: #607286;
          font-size: 11 * 2px;
          font-weight: 400;
        }
      }
    }
    &-right {
      text-wrap: nowrap;
      white-space: nowrap;
      border-radius: 100px;
      background: #007bff;
      padding: 4 * 2px 10 * 2px;
      color: #fff;
      font-size: 13 * 2px;
      font-weight: 590;
      margin-left: 8 * 2px;
    }
  }
}

.slzLoader {
  position: absolute;
  top: 32.5 * 2px;
  left: 50%;
  transform: translateX(-50%);
  width: 22px;
  aspect-ratio: 4;
  --_g: no-repeat radial-gradient(circle closest-side, #007bff 90%, #0000);
  background: var(--_g) 0% 50%, var(--_g) 50% 50%, var(--_g) 100% 50%;
  background-size: calc(100% / 3) 100%;
  animation: l7 1s infinite linear;
}
@keyframes l7 {
  33% {
    background-size: calc(100% / 3) 0%, calc(100% / 3) 100%, calc(100% / 3) 100%;
  }
  50% {
    background-size: calc(100% / 3) 100%, calc(100% / 3) 0%, calc(100% / 3) 100%;
  }
  66% {
    background-size: calc(100% / 3) 100%, calc(100% / 3) 100%, calc(100% / 3) 0%;
  }
}

.inviteFriends {
  border-radius: 12 * 2px;
  background: #fff;
  padding: 10 * 2px;
  margin: 0 15 * 2px;
  margin-top: 10 * 2px;
  &-end {
    margin: 10 * 2px 0 0;
  }

  &-title {
    justify-content: space-between;
    padding-bottom: 10 * 2px;
    margin-bottom: 10 * 2px;
    border-bottom: 0.7px solid rgba(115, 119, 128, 0.15);

    &-text {
      color: #161817;
      font-size: 13 * 2px;
      font-weight: 590;
    }
    &-img {
      width: 10 * 2px;
      height: 10 * 2px;
    }
  }
  &-info {
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    position: relative;
    background: linear-gradient(90deg, #afe7f1 0%, #d7ecff 100%);
    border-radius: 12 * 2px;
    min-height: 90 * 2px;
    overflow: hidden;

    &-leftimg {
      position: absolute;
      top: 0;
      left: 0;
      width: 70 * 2px;
    }
    &-rightimg {
      position: absolute;
      top: 0;
      right: 0;
      width: 70 * 2px;
    }
    &-logo {
      position: absolute;
      top: 5 * 2px;
      right: 10 * 2px;
      width: 90 * 2px;
    }
    &-title {
      position: relative;
      z-index: 5;
      width: calc(100% - 90 * 2px);
      background: linear-gradient(
        90deg,
        #8adbe9 0%,
        rgba(162, 227, 239, 0) 100%
      );
      padding: 6 * 2px 0 6 * 2px 12 * 2px;
      color: #002853;
      font-size: 12 * 2px;
      font-weight: 590;
      margin-bottom: 5 * 2px;
    }
    &-desc {
      position: relative;
      z-index: 5;
      width: calc(100% - 90 * 2px);
      color: #607286;
      font-size: 11 * 2px;
      font-weight: 400;
      padding-left: 12 * 2px;
    }
  }
}
</style>
